From 8da6c7584c7d1165a83446ec0e421bfc980db9cb Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 12:40:58 +0800 Subject: [PATCH 01/16] =?UTF-8?q?feat:=20pipeline=20compilation=20phase=20?= =?UTF-8?q?1=20=E2=80=94=20tracer,=20plan=20IR,=20generic=20executor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gpu.createPipeline(fn, { constants }) traces the orchestration function once at first call against frozen Proxy handles, unrolls it into a static plan (steps / argBindings / buffers / results per the design contract), assigns buffers by static liveness with automatic double-buffering (the ping-pong loop compiles to ONE kernel over two alternating slots), and executes through per-pipeline kernel clones configured pipeline+immutable so intermediates stay resident with a single final readback. Calls always return a Promise and serialize on a tail; setConstants invalidates and re-traces; destroy releases clones and is reachable from gpu.destroy via the new pipeline registry. executorKind = 'generic' on every backend -- the webasm fused executors are phase 2. Trace interception lives in kernel-run-shortcut (a call under an open trace records instead of running), so user-visible kernels are never monkey-patched. Trace violations (handle reads/arithmetic, Math.random, foreign kernels, graphical, kernel maps, unsized kernels, bad returns) reject the building call with named messages. 51 tests across trace-rules/correctness/buffers/lifecycle, correctness proven against plain-JS references on cpu, webasm, and headlessgl; all behavioral tests verified discriminating against 16 hand-applied mutations (including GL texture-census and single-readback probes). Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 341 +++++++++++++++++- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 341 +++++++++++++++++- dist/gpu-browser.min.js | 4 +- docs/design/pipeline-compilation.md | 117 ++++++ src/gpu.js | 51 +++ src/index.d.ts | 36 ++ src/kernel-run-shortcut.js | 9 + src/pipeline.js | 495 ++++++++++++++++++++++++++ test/all.html | 4 + test/features/pipeline/buffers.js | 106 ++++++ test/features/pipeline/correctness.js | 171 +++++++++ test/features/pipeline/lifecycle.js | 207 +++++++++++ test/features/pipeline/trace-rules.js | 167 +++++++++ 14 files changed, 2047 insertions(+), 6 deletions(-) create mode 100644 docs/design/pipeline-compilation.md create mode 100644 src/pipeline.js create mode 100644 test/features/pipeline/buffers.js create mode 100644 test/features/pipeline/correctness.js create mode 100644 test/features/pipeline/lifecycle.js create mode 100644 test/features/pipeline/trace-rules.js diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 97f78d10..4eed96de 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:06:42 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -19063,9 +19063,316 @@ } }; }); + var require_pipeline = __commonJSMin((exports, module) => { + const {Input: Input} = require_input(); + const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; + const MSG_HANDLE_PRIMITIVE = "pipeline intermediate results cannot be used in arithmetic or conditions during orchestration"; + const MSG_MATH_RANDOM = "Math.random() is not allowed during pipeline orchestration; orchestration must be deterministic"; + const MSG_FOREIGN_KERNEL = "pipelines can only call kernels created by the same GPU instance"; + const MSG_GRAPHICAL = "graphical kernels are not supported inside pipelines"; + const MSG_KERNEL_MAP = "kernel maps are not supported inside pipelines"; + const MSG_RETURN_SHAPE = "a pipeline must return a handle, or an Array or plain object of handles"; + const MSG_FIXED_OUTPUT = "kernels called inside a pipeline must have a fixed output size"; + const MSG_DESTROYED = "pipeline has been destroyed"; + var PipelineHandle = class {}; + let activeTrace = null; + function getActiveTrace() { + return activeTrace; + } + var PipelineTrace = class { + constructor(gpu) { + this.gpu = gpu; + this.steps = []; + this.kernels = []; + this.kernelIndexes = new Map; + this.handleMeta = new WeakMap; + } + createHandle(meta) { + const trace = this; + const target = Object.freeze(new PipelineHandle); + const handle = new Proxy(target, { + get(_, property) { + if (property === Symbol.toPrimitive || property === "valueOf" || property === "toString") return () => { + throw new Error(MSG_HANDLE_PRIMITIVE); + }; + throw new Error(MSG_HANDLE_READ); + }, + set() { + throw new Error(MSG_HANDLE_READ); + } + }); + trace.handleMeta.set(handle, meta); + return handle; + } + recordKernelCall(shortcut, args) { + const kernel = shortcut.kernel; + if (kernel.gpu !== this.gpu) throw new Error(MSG_FOREIGN_KERNEL); + if (kernel.graphical) throw new Error(MSG_GRAPHICAL); + if (kernel.subKernels && kernel.subKernels.length > 0) throw new Error(MSG_KERNEL_MAP); + if (!kernel.output) throw new Error(MSG_FIXED_OUTPUT); + let kernelIndex = this.kernelIndexes.get(shortcut); + if (kernelIndex === void 0) { + kernelIndex = this.kernels.length; + this.kernels.push(shortcut); + this.kernelIndexes.set(shortcut, kernelIndex); + } + const argBindings = new Array(args.length); + for (let i = 0; i < args.length; i++) argBindings[i] = this.bindValue(args[i]); + const stepIndex = this.steps.length; + this.steps.push({ + kernel: kernelIndex, + argBindings: argBindings, + output: Array.from(kernel.output), + outputBuffer: -1 + }); + return this.createHandle({ + source: "step", + step: stepIndex + }); + } + bindValue(value) { + const meta = this.handleMeta.get(value); + if (meta) return meta; + return { + source: "literal", + value: snapshotValue(value) + }; + } + }; + function snapshotValue(value) { + if (!value || typeof value !== "object") return value; + if (typeof value.delete === "function" || typeof value.toArray === "function") return value; + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(snapshotValue); + if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + return value; + } + function assignBuffers(steps, resultBindings) { + const lastRead = new Array(steps.length).fill(-1); + for (let i = 0; i < steps.length; i++) { + const bindings = steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step") lastRead[binding.step] = Math.max(lastRead[binding.step], i); + } + } + for (let i = 0; i < resultBindings.length; i++) { + const binding = resultBindings[i]; + if (binding.source === "step") lastRead[binding.step] = steps.length; + } + const buffers = []; + const occupantLastRead = []; + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + let assigned = -1; + for (let b = 0; b < buffers.length; b++) if (occupantLastRead[b] < i && sameShape(buffers[b].output, step.output)) { + assigned = b; + break; + } + if (assigned === -1) { + assigned = buffers.length; + buffers.push({ + output: step.output.slice() + }); + occupantLastRead.push(-1); + } + step.outputBuffer = assigned; + occupantLastRead[assigned] = lastRead[i]; + } + return buffers; + } + function sameShape(a, b) { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + return true; + } + function bindResults(trace, returned) { + if (returned === null || returned === void 0) throw new Error(MSG_RETURN_SHAPE); + if (trace.handleMeta.has(returned)) return { + kind: "single", + entries: [ { + binding: trace.bindValue(returned) + } ] + }; + if (Array.isArray(returned)) return { + kind: "array", + entries: returned.map((value, i) => ({ + key: i, + binding: trace.bindValue(value) + })) + }; + if (typeof returned === "object" && !ArrayBuffer.isView(returned)) { + const entries = []; + for (const key in returned) { + if (!returned.hasOwnProperty(key)) continue; + entries.push({ + key: key, + binding: trace.bindValue(returned[key]) + }); + } + return { + kind: "object", + entries: entries + }; + } + throw new Error(MSG_RETURN_SHAPE); + } + var Pipeline = class { + constructor(gpu, fn, settings) { + settings = settings || {}; + this.gpu = gpu; + this.fn = fn; + this.argumentCount = fn.length; + this.constants = Object.assign({}, settings.constants || {}); + this.plan = null; + this.executorKind = "generic"; + this.destroyed = false; + this._tail = Promise.resolve(); + } + call(args) { + if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); + const sampled = new Array(args.length); + for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); + const promise = this._tail.then(() => { + if (this.destroyed) throw new Error(MSG_DESTROYED); + if (!this.plan) this.plan = this._buildPlan(); + return this._executeGeneric(this.plan, sampled); + }); + this._tail = promise.then(noop, noop); + return promise; + } + setConstants(constants) { + this.constants = Object.assign({}, constants || {}); + const release = () => { + this._releasePlan(); + }; + this._tail = this._tail.then(release, release); + return this; + } + destroy() { + this.destroyed = true; + if (this.gpu && this.gpu.pipelines) { + const index = this.gpu.pipelines.indexOf(this); + if (index !== -1) this.gpu.pipelines.splice(index, 1); + } + const release = () => { + this._releasePlan(); + }; + const tail = this._tail.then(release, release); + this._tail = tail; + return tail; + } + _buildPlan() { + const trace = new PipelineTrace(this.gpu); + const argHandles = new Array(this.argumentCount); + for (let i = 0; i < this.argumentCount; i++) argHandles[i] = trace.createHandle({ + source: "pipelineArg", + index: i + }); + const originalRandom = Math.random; + Math.random = function pipelineTraceRandom() { + throw new Error(MSG_MATH_RANDOM); + }; + activeTrace = trace; + let returned; + try { + returned = this.fn.apply({ + constants: Object.assign({}, this.constants) + }, argHandles); + } finally { + activeTrace = null; + Math.random = originalRandom; + } + const results = bindResults(trace, returned); + const buffers = assignBuffers(trace.steps, results.entries.map(entry => entry.binding)); + const kernels = trace.kernels.map(shortcut => ({ + shortcut: shortcut, + clone: this._cloneKernel(shortcut) + })); + return { + steps: trace.steps, + buffers: buffers, + results: results, + kernels: kernels + }; + } + _cloneKernel(shortcut) { + const kernel = shortcut.kernel; + const settings = { + output: Array.from(kernel.output), + pipeline: true, + immutable: true, + dynamicArguments: true + }; + const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug" ]; + for (let i = 0; i < optional.length; i++) { + const name = optional[i]; + if (kernel[name] !== null && kernel[name] !== void 0) settings[name] = kernel[name]; + } + return this.gpu.createKernel(kernel.source, settings); + } + async _executeGeneric(plan, args) { + const slots = new Array(plan.buffers.length).fill(null); + try { + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const bindings = step.argBindings; + const resolved = new Array(bindings.length); + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "pipelineArg") resolved[j] = args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; + } + let output = plan.kernels[step.kernel].clone.apply(null, resolved); + if (output && typeof output.then === "function") output = await output; + releaseValue(slots[step.outputBuffer]); + slots[step.outputBuffer] = output; + } + const results = plan.results; + const values = new Array(results.entries.length); + for (let i = 0; i < results.entries.length; i++) { + const binding = results.entries[i].binding; + let value; + if (binding.source === "pipelineArg") value = args[binding.index]; else if (binding.source === "step") value = slots[plan.steps[binding.step].outputBuffer]; else value = binding.value; + if (value && typeof value.toArray === "function") { + value = value.toArray(); + if (value && typeof value.then === "function") value = await value; + } + values[i] = value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < results.entries.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } finally { + for (let i = 0; i < slots.length; i++) releaseValue(slots[i]); + } + } + _releasePlan() { + if (!this.plan) return; + const kernels = this.plan.kernels; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < kernels.length; i++) { + const clone = kernels[i].clone; + if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + } + this.plan = null; + } + }; + function releaseValue(value) { + if (value && typeof value.delete === "function") value.delete(); + } + function noop() {} + module.exports = { + Pipeline: Pipeline, + PipelineHandle: PipelineHandle, + getActiveTrace: getActiveTrace + }; + }); var require_kernel_run_shortcut = __commonJSMin((exports, module) => { const {utils: utils} = require_utils(); const {Input: Input} = require_input(); + const {getActiveTrace: getActiveTrace} = require_pipeline(); function kernelRunShortcut(kernel) { const MAX_SWITCHES = 4; function syncBody(args) { @@ -19150,6 +19457,8 @@ return value; } function run() { + const trace = getActiveTrace(); + if (trace) return trace.recordKernelCall(shortcut, arguments); if (kernel.constructor.isAsync === true || kernel.asyncMode === true) return asyncRun(arguments); return syncRun(arguments); } @@ -19210,6 +19519,7 @@ const {WebGPUKernel: WebGPUKernel} = require_kernel$1(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); const {kernelRunShortcut: kernelRunShortcut} = require_kernel_run_shortcut(); + const {Pipeline: Pipeline} = require_pipeline(); const kernelOrder = [ HeadlessGLKernel, WebGL2Kernel, WebGLKernel, WebAssemblyKernel ]; const kernelTypes = [ "gpu", "cpu" ]; const internalKernels = { @@ -19277,6 +19587,7 @@ this._webGPUDecision = false; }); else this._webGPUDecision = false; this.kernels = []; + this.pipelines = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; @@ -19519,6 +19830,30 @@ kernels.push(kernel); return kernelRun; } + createPipeline(fn, settings) { + if (typeof fn !== "function") throw new Error("createPipeline requires an orchestration function"); + if (this.mode === "dev") throw new Error("createPipeline is not supported in dev mode"); + const pipeline = new Pipeline(this, fn, settings); + this.pipelines.push(pipeline); + const shortcut = function() { + return pipeline.call(arguments); + }; + shortcut.pipeline = pipeline; + shortcut.setConstants = function(constants) { + pipeline.setConstants(constants); + return shortcut; + }; + shortcut.destroy = function() { + return pipeline.destroy(); + }; + Object.defineProperty(shortcut, "executorKind", { + get: () => pipeline.executorKind + }); + Object.defineProperty(shortcut, "plan", { + get: () => pipeline.plan + }); + return shortcut; + } createKernelMap() { let fn; let settings; @@ -19611,6 +19946,10 @@ if (!this.kernels) resolve(); setTimeout(() => { try { + if (this.pipelines) { + const pipelines = this.pipelines.slice(); + for (let i = 0; i < pipelines.length; i++) pipelines[i].destroy(); + } const kernels = this.kernels.slice(); for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); let firstKernel = kernels[0]; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index f5564e73..58567938 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:06:42 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>f,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):m.test(e)&&(e=e.replace(m,"u_u")),e}},p=/\$/,d=/__/,m=/_/,f=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:m,optimizeFloatMemory:f,precision:g,plugins:y,source:x,subKernels:b,functions:T,leadingReturnStatement:v,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),L=(e,t,r)=>{B.assignArgumentType(e,t,r)},F=(e,t,r)=>B.lookupReturnType(e,t,r),k=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:m,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:f,precision:g,lookupReturnType:F,lookupFunctionArgumentTypes:k,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:L,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},N,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function m(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(f(e.body,t),e):e}function f(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return m(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(m(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=m();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=F();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=F();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=F();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=f(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=T(),{GLTextureArray4Float:p}=v(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=m(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:N}=I(),{GLTextureMemoryOptimized2D:O}=_(),{GLTextureMemoryOptimized3D:z}=L(),{GLTextureUnsigned:V}=F(),{GLTextureUnsigned2D:U}=k(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=N,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},m={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),N=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),O=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return f;case"insertVariable":return b;case"reset":return x;case"setIndent":return v;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:T,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;f=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],T(arguments[4]),T(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(m[e[p]]=p,e[p])}}),d=[],m={};let f,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function T(e){const t=m[e];return t?r+"."+t:e}function v(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:m,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${f(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${f(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${f(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${f(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${f(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function m(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function f(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:m,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=O(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(m){const t=R.subKernels[f++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),m=!0;f===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let m=!1,f=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:F,argumentTypes:k,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:F,argumentTypes:k,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let N=[];return C.forEach(e=>{N.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${N.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=fe();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:m}=te(),{WebGLKernelValueNumberTexture:f}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:T}=oe(),{WebGLKernelValueSingleArray2DI:v}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=me(),{WebGLKernelValueUnsignedArray:L}=fe(),{WebGLKernelValueDynamicUnsignedArray:F}=ge(),k={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:F,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:m,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:f,"ArrayTexture(1)":f,"ArrayTexture(2)":f,"ArrayTexture(3)":f,"ArrayTexture(4)":f,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:m,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":v,"Array2D(3)":v,"Array2D(4)":v,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:f,"ArrayTexture(1)":f,"ArrayTexture(2)":f,"ArrayTexture(3)":f,"ArrayTexture(4)":f,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=k[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:k}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=N(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,m=null,f=null,g=null,y=null;const x=[u],b=[],T={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(f)),d}static setupFeatureChecks(){"undefined"!=typeof document?m=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(m=new OffscreenCanvas(0,0)),m&&(f=m.getContext("webgl"),f||m instanceof OffscreenCanvas||(f=m.getContext("experimental-webgl")),f&&f.getExtension&&(g={OES_texture_float:f.getExtension("OES_texture_float"),OES_texture_float_linear:f.getExtension("OES_texture_float_linear"),OES_element_index_uint:f.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:f.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?f.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return f.getParameter(f.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return m}static get testContext(){return f}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),T[r]=[e[0],e[1]]),this.maxTexSize=T[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const m=r.getAttribLocation(this.program,"aPos");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0));const f=r.getAttribLocation(this.program,"aTexCoord");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,T[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Te=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),ve=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=Le();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=me();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=fe();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=Le(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Fe(),{WebGL2KernelValueHTMLVideo:l}=ke(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:m}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:f}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Ne(),{WebGL2KernelValueNumberTexture:y}=Oe(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:T}=Ue(),{WebGL2KernelValueSingleArray1DI:v}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:L}=He(),{WebGL2KernelValueArray4:F}=Ye(),{WebGL2KernelValueUnsignedArray:k}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":L,"Array(4)":F,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:m,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":L,"Array(4)":F,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:T,"Array(2)":_,"Array(3)":L,"Array(4)":F,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":L,"Array(4)":F,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:f,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=Te(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=ve(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,m=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),m=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return m}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),m={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in m)new RegExp(`\\b${e}\\(`).test(a)&&n.push(m[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},m={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},f={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},T={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function v(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>v("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=T[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let m=null,f=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===m)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),m=WebAssembly.validate(e.toBytes())}catch(e){m=!1}return m}static get isThreadsSupported(){if(null===f)try{if("undefined"==typeof SharedArrayBuffer)f=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),f=!0}}catch(e){f=!1}return f}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,m=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(m.localGet(0).localSet(3),1===this.output.length?(m.i32Const(0).globalSet(h.threadY),m.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&m.i32Const(0).globalSet(h.threadZ),m.block(),m.localGet(3).localGet(1).i32GeS().brIf(0),m.loop(),m.localGet(3).globalSet(h.dataIndex),1===this.output.length?m.localGet(3).globalSet(h.threadX):2===this.output.length?(m.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),m.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(m.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),m.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),m.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&m.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),m.call("kernel"),m.localGet(3).i32Const(1).i32Add().localSet(3),m.localGet(3).localGet(1).i32LtS().brIf(0),m.end(),m.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const m=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),f={env:{memory:m}};for(const e of this.usedMathImports)f.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,f);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:m,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(m.buffer),i32:new Int32Array(m.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),u|=0,o&&n>0){const t=e[0];if(3&t){const e=-4&t,r=n/t;for(let n=0;n0&&o(r,r+e,u),a(r+e,r+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,n,u),this._lastRunPath="simd"}else a(0,n,u),this._lastRunPath="scalar";const l=r.outputOffset/4,h=s.slice(l,l+n*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const m=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),f=this._threadedEpoch,g=()=>{this._threadedEpoch===f&&this._threadedBusy--};return this._threadedTail=m.then(g,g),m}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n();function a(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);c.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=u(r);return t(s,e).then(e=>(e&&c.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function o(e){const t=u(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function u(e){const t=new Array(e.length);for(let r=0;r{try{e(h.apply(this,arguments))}catch(e){t(e)}})},c.replaceKernel=function(t){a(e=t,c)},a(e,c),c}}}),ht=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:m}=ut(),{kernelRunShortcut:f}=lt(),g=[l,h,c,m],y=["gpu","cpu"],x={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:m};let b=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){b=!1}static enableValidation(){b=!0}static get isGPUSupported(){return g.some(e=>e.isSupported)}static get isKernelMapSupported(){return g.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return m.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return g.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:b,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:b,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let m,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{m=new g(t,p)}catch(e){if(g===this.Kernel)throw e;m=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=f(m);if("async"===this.mode&&d.isSupported&&!(m instanceof d)){const r=this;m.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:b,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=m.canvas),this.context||(this.context=m.context),i.push(m),y}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&y.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),pt=e((e,t)=>{const{GPU:r}=ht(),{alias:c}=ct(),{utils:d}=i(),{Input:m,input:f}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:T}=p(),{HeadlessGLKernel:v}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=Te(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:L}=tt(),{WebGPUKernel:F}=st(),{WebGPUContext:k}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:N}=C(),{Kernel:O}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:T,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:v,Input:m,input:f,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:L,WebGPUKernel:F,WebGPUContext:k,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:M,GLKernel:N,Kernel:O,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=pt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:T,leadingReturnStatement:v,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),L=(e,t,r)=>{B.assignArgumentType(e,t,r)},k=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},M=(e,t,r)=>{B.trackFunctionCall(e,t,r)},R=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:k,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:L,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:M,onNestedFunction:R})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=k();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=T(),{GLTextureArray4Float:p}=v(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:M}=w(),{GLTextureFloat3D:R}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=L(),{GLTextureUnsigned:V}=k(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=R,null):this.output[1]>0?(this.TextureConstructor=M,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=R,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=M,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),R=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return v;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:T,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],T(arguments[4]),T(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function T(e){const t=f[e];return t?r+"."+t:e}function v(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(M.subKernels){if(f){const t=M.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,M)};`)}else p.push(` const result = { result: ${a(e,M)} };`),f=!0;m===M.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,M)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,M.kernelArguments,[],d,c);if(t)return t;const r=u(e,M.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,M=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,tactic:G});let R=[];if(d.setIndent(2),M.build.apply(M,t),R.push(d.toString()),d.reset(),M.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),M.run.apply(M,t),M.renderKernels?M.renderKernels():M.renderOutput&&M.renderOutput(),R.push(" /** start setup uploads for kernel values **/"),M.kernelArguments.forEach(e=>{R.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),R.push(" /** end setup uploads for kernel values **/"),R.push(d.toString()),M.renderOutput===M.renderTexture)if(d.reset(),M.renderKernels){const e=M.renderKernels(),t=d.getContextVariableName(M.texture.texture);R.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=M;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(M)),R.push(" innerKernel.getPixels = getPixels;")),R.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${R.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:T}=oe(),{WebGLKernelValueSingleArray2DI:v}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:L}=me(),{WebGLKernelValueDynamicUnsignedArray:k}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":v,"Array2D(3)":v,"Array2D(4)":v,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=M(),{fragmentShader:l}=R(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],T={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),T[r]=[e[0],e[1]]),this.maxTexSize=T[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,T[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Te=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),ve=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=Le();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=Le(),{WebGL2KernelValueDynamicHTMLImageArray:u}=ke(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Re(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:T}=Ue(),{WebGL2KernelValueSingleArray1DI:v}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:L}=He(),{WebGL2KernelValueArray4:k}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:T,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=Te(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=ve(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},T={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function v(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>v("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=T[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),u|=0,o&&n>0){const t=e[0];if(3&t){const e=-4&t,r=n/t;for(let n=0;n0&&o(r,r+e,u),a(r+e,r+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,n,u),this._lastRunPath="simd"}else a(0,n,u),this._lastRunPath="scalar";const l=r.outputOffset/4,h=s.slice(l,l+n*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);return this.plan||(this.plan=this._buildPlan()),this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=lt();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ct=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ht(),{Pipeline:g}=lt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let T=!0;function v(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){T=!1}static enableValidation(){T=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:T,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:T,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:T,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=v(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),dt=e((e,t)=>{const{GPU:r}=ct(),{alias:c}=pt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:T}=p(),{HeadlessGLKernel:v}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=Te(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:L}=tt(),{WebGPUKernel:k}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:R}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:T,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:v,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:L,WebGPUKernel:k,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:R,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:M()}}});return e((e,t)=>{const r=dt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index abc4617a..43cb7196 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:06:42 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -23260,9 +23260,316 @@ } }; }); + var require_pipeline = __commonJSMin((exports, module) => { + const {Input: Input} = require_input(); + const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; + const MSG_HANDLE_PRIMITIVE = "pipeline intermediate results cannot be used in arithmetic or conditions during orchestration"; + const MSG_MATH_RANDOM = "Math.random() is not allowed during pipeline orchestration; orchestration must be deterministic"; + const MSG_FOREIGN_KERNEL = "pipelines can only call kernels created by the same GPU instance"; + const MSG_GRAPHICAL = "graphical kernels are not supported inside pipelines"; + const MSG_KERNEL_MAP = "kernel maps are not supported inside pipelines"; + const MSG_RETURN_SHAPE = "a pipeline must return a handle, or an Array or plain object of handles"; + const MSG_FIXED_OUTPUT = "kernels called inside a pipeline must have a fixed output size"; + const MSG_DESTROYED = "pipeline has been destroyed"; + var PipelineHandle = class {}; + let activeTrace = null; + function getActiveTrace() { + return activeTrace; + } + var PipelineTrace = class { + constructor(gpu) { + this.gpu = gpu; + this.steps = []; + this.kernels = []; + this.kernelIndexes = new Map; + this.handleMeta = new WeakMap; + } + createHandle(meta) { + const trace = this; + const target = Object.freeze(new PipelineHandle); + const handle = new Proxy(target, { + get(_, property) { + if (property === Symbol.toPrimitive || property === "valueOf" || property === "toString") return () => { + throw new Error(MSG_HANDLE_PRIMITIVE); + }; + throw new Error(MSG_HANDLE_READ); + }, + set() { + throw new Error(MSG_HANDLE_READ); + } + }); + trace.handleMeta.set(handle, meta); + return handle; + } + recordKernelCall(shortcut, args) { + const kernel = shortcut.kernel; + if (kernel.gpu !== this.gpu) throw new Error(MSG_FOREIGN_KERNEL); + if (kernel.graphical) throw new Error(MSG_GRAPHICAL); + if (kernel.subKernels && kernel.subKernels.length > 0) throw new Error(MSG_KERNEL_MAP); + if (!kernel.output) throw new Error(MSG_FIXED_OUTPUT); + let kernelIndex = this.kernelIndexes.get(shortcut); + if (kernelIndex === void 0) { + kernelIndex = this.kernels.length; + this.kernels.push(shortcut); + this.kernelIndexes.set(shortcut, kernelIndex); + } + const argBindings = new Array(args.length); + for (let i = 0; i < args.length; i++) argBindings[i] = this.bindValue(args[i]); + const stepIndex = this.steps.length; + this.steps.push({ + kernel: kernelIndex, + argBindings: argBindings, + output: Array.from(kernel.output), + outputBuffer: -1 + }); + return this.createHandle({ + source: "step", + step: stepIndex + }); + } + bindValue(value) { + const meta = this.handleMeta.get(value); + if (meta) return meta; + return { + source: "literal", + value: snapshotValue(value) + }; + } + }; + function snapshotValue(value) { + if (!value || typeof value !== "object") return value; + if (typeof value.delete === "function" || typeof value.toArray === "function") return value; + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(snapshotValue); + if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + return value; + } + function assignBuffers(steps, resultBindings) { + const lastRead = new Array(steps.length).fill(-1); + for (let i = 0; i < steps.length; i++) { + const bindings = steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step") lastRead[binding.step] = Math.max(lastRead[binding.step], i); + } + } + for (let i = 0; i < resultBindings.length; i++) { + const binding = resultBindings[i]; + if (binding.source === "step") lastRead[binding.step] = steps.length; + } + const buffers = []; + const occupantLastRead = []; + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + let assigned = -1; + for (let b = 0; b < buffers.length; b++) if (occupantLastRead[b] < i && sameShape(buffers[b].output, step.output)) { + assigned = b; + break; + } + if (assigned === -1) { + assigned = buffers.length; + buffers.push({ + output: step.output.slice() + }); + occupantLastRead.push(-1); + } + step.outputBuffer = assigned; + occupantLastRead[assigned] = lastRead[i]; + } + return buffers; + } + function sameShape(a, b) { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; + return true; + } + function bindResults(trace, returned) { + if (returned === null || returned === void 0) throw new Error(MSG_RETURN_SHAPE); + if (trace.handleMeta.has(returned)) return { + kind: "single", + entries: [ { + binding: trace.bindValue(returned) + } ] + }; + if (Array.isArray(returned)) return { + kind: "array", + entries: returned.map((value, i) => ({ + key: i, + binding: trace.bindValue(value) + })) + }; + if (typeof returned === "object" && !ArrayBuffer.isView(returned)) { + const entries = []; + for (const key in returned) { + if (!returned.hasOwnProperty(key)) continue; + entries.push({ + key: key, + binding: trace.bindValue(returned[key]) + }); + } + return { + kind: "object", + entries: entries + }; + } + throw new Error(MSG_RETURN_SHAPE); + } + var Pipeline = class { + constructor(gpu, fn, settings) { + settings = settings || {}; + this.gpu = gpu; + this.fn = fn; + this.argumentCount = fn.length; + this.constants = Object.assign({}, settings.constants || {}); + this.plan = null; + this.executorKind = "generic"; + this.destroyed = false; + this._tail = Promise.resolve(); + } + call(args) { + if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); + const sampled = new Array(args.length); + for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); + const promise = this._tail.then(() => { + if (this.destroyed) throw new Error(MSG_DESTROYED); + if (!this.plan) this.plan = this._buildPlan(); + return this._executeGeneric(this.plan, sampled); + }); + this._tail = promise.then(noop, noop); + return promise; + } + setConstants(constants) { + this.constants = Object.assign({}, constants || {}); + const release = () => { + this._releasePlan(); + }; + this._tail = this._tail.then(release, release); + return this; + } + destroy() { + this.destroyed = true; + if (this.gpu && this.gpu.pipelines) { + const index = this.gpu.pipelines.indexOf(this); + if (index !== -1) this.gpu.pipelines.splice(index, 1); + } + const release = () => { + this._releasePlan(); + }; + const tail = this._tail.then(release, release); + this._tail = tail; + return tail; + } + _buildPlan() { + const trace = new PipelineTrace(this.gpu); + const argHandles = new Array(this.argumentCount); + for (let i = 0; i < this.argumentCount; i++) argHandles[i] = trace.createHandle({ + source: "pipelineArg", + index: i + }); + const originalRandom = Math.random; + Math.random = function pipelineTraceRandom() { + throw new Error(MSG_MATH_RANDOM); + }; + activeTrace = trace; + let returned; + try { + returned = this.fn.apply({ + constants: Object.assign({}, this.constants) + }, argHandles); + } finally { + activeTrace = null; + Math.random = originalRandom; + } + const results = bindResults(trace, returned); + const buffers = assignBuffers(trace.steps, results.entries.map(entry => entry.binding)); + const kernels = trace.kernels.map(shortcut => ({ + shortcut: shortcut, + clone: this._cloneKernel(shortcut) + })); + return { + steps: trace.steps, + buffers: buffers, + results: results, + kernels: kernels + }; + } + _cloneKernel(shortcut) { + const kernel = shortcut.kernel; + const settings = { + output: Array.from(kernel.output), + pipeline: true, + immutable: true, + dynamicArguments: true + }; + const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug" ]; + for (let i = 0; i < optional.length; i++) { + const name = optional[i]; + if (kernel[name] !== null && kernel[name] !== void 0) settings[name] = kernel[name]; + } + return this.gpu.createKernel(kernel.source, settings); + } + async _executeGeneric(plan, args) { + const slots = new Array(plan.buffers.length).fill(null); + try { + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const bindings = step.argBindings; + const resolved = new Array(bindings.length); + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "pipelineArg") resolved[j] = args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; + } + let output = plan.kernels[step.kernel].clone.apply(null, resolved); + if (output && typeof output.then === "function") output = await output; + releaseValue(slots[step.outputBuffer]); + slots[step.outputBuffer] = output; + } + const results = plan.results; + const values = new Array(results.entries.length); + for (let i = 0; i < results.entries.length; i++) { + const binding = results.entries[i].binding; + let value; + if (binding.source === "pipelineArg") value = args[binding.index]; else if (binding.source === "step") value = slots[plan.steps[binding.step].outputBuffer]; else value = binding.value; + if (value && typeof value.toArray === "function") { + value = value.toArray(); + if (value && typeof value.then === "function") value = await value; + } + values[i] = value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < results.entries.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } finally { + for (let i = 0; i < slots.length; i++) releaseValue(slots[i]); + } + } + _releasePlan() { + if (!this.plan) return; + const kernels = this.plan.kernels; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < kernels.length; i++) { + const clone = kernels[i].clone; + if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + } + this.plan = null; + } + }; + function releaseValue(value) { + if (value && typeof value.delete === "function") value.delete(); + } + function noop() {} + module.exports = { + Pipeline: Pipeline, + PipelineHandle: PipelineHandle, + getActiveTrace: getActiveTrace + }; + }); var require_kernel_run_shortcut = __commonJSMin((exports, module) => { const {utils: utils} = require_utils(); const {Input: Input} = require_input(); + const {getActiveTrace: getActiveTrace} = require_pipeline(); function kernelRunShortcut(kernel) { const MAX_SWITCHES = 4; function syncBody(args) { @@ -23347,6 +23654,8 @@ return value; } function run() { + const trace = getActiveTrace(); + if (trace) return trace.recordKernelCall(shortcut, arguments); if (kernel.constructor.isAsync === true || kernel.asyncMode === true) return asyncRun(arguments); return syncRun(arguments); } @@ -23407,6 +23716,7 @@ const {WebGPUKernel: WebGPUKernel} = require_kernel$1(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); const {kernelRunShortcut: kernelRunShortcut} = require_kernel_run_shortcut(); + const {Pipeline: Pipeline} = require_pipeline(); const kernelOrder = [ HeadlessGLKernel, WebGL2Kernel, WebGLKernel, WebAssemblyKernel ]; const kernelTypes = [ "gpu", "cpu" ]; const internalKernels = { @@ -23474,6 +23784,7 @@ this._webGPUDecision = false; }); else this._webGPUDecision = false; this.kernels = []; + this.pipelines = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; @@ -23716,6 +24027,30 @@ kernels.push(kernel); return kernelRun; } + createPipeline(fn, settings) { + if (typeof fn !== "function") throw new Error("createPipeline requires an orchestration function"); + if (this.mode === "dev") throw new Error("createPipeline is not supported in dev mode"); + const pipeline = new Pipeline(this, fn, settings); + this.pipelines.push(pipeline); + const shortcut = function() { + return pipeline.call(arguments); + }; + shortcut.pipeline = pipeline; + shortcut.setConstants = function(constants) { + pipeline.setConstants(constants); + return shortcut; + }; + shortcut.destroy = function() { + return pipeline.destroy(); + }; + Object.defineProperty(shortcut, "executorKind", { + get: () => pipeline.executorKind + }); + Object.defineProperty(shortcut, "plan", { + get: () => pipeline.plan + }); + return shortcut; + } createKernelMap() { let fn; let settings; @@ -23808,6 +24143,10 @@ if (!this.kernels) resolve(); setTimeout(() => { try { + if (this.pipelines) { + const pipelines = this.pipelines.slice(); + for (let i = 0; i < pipelines.length; i++) pipelines[i].destroy(); + } const kernels = this.kernels.slice(); for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); let firstKernel = kernels[0]; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 7162c455..215e3384 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:06:42 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var N=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,R=function(e,t){this.line=e,this.column=t};R.prototype.offset=function(e){return new R(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new R(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function U(e,t){return 2|(e?4:0)|(t?8:0)}var B=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};B.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},B.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,E.lastIndex=e,e+=E.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;E.lastIndex=this.pos;var e,t=E.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){E.lastIndex=this.pos;var a=E.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(U(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return N.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=B.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|U(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|U(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=B.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Ee=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",_e=Ee+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:Ee,13:_e,14:_e+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Re(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Ue(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Be(e){return e>=48&&e<=55}Ne.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Ne.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Ne.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Ne.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Ne.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Ne.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Ne.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Ne.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Ne.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Re(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Be(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Ue(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Be(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Ne(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(n.length),_={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,s)=>{U.assignArgumentType(e,t,s)},C=(e,t,s)=>U.lookupReturnType(e,t,s),L=e=>U.lookupFunctionArgumentTypes(e),D=(e,t)=>U.lookupFunctionArgumentName(e,t),F=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{U.assignArgumentType(e,t,s,r)},N=(e,t,s,r)=>{U.assignArgumentBitRatio(e,t,s,r)},R=(e,t,s)=>{U.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:_,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:N,onFunctionCall:R,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),N=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:N}=m(),{GLTextureFloat2D:R}=E(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:U}=F(),{GLTextureGraphical:B}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=B,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=N,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=N,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return _}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function _(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const s=u(e,R.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:N}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:N});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=R;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=U(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=U();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=U();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=U();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=B(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:E}=de(),{WebGLKernelValueArray3:_}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=N(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=R(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=R();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=B();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),Ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=Ee(),{WebGL2KernelValueInteger:n}=_e(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Ne(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:S}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:E}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:_}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),u|=0,o&&r>0){const t=e[0];if(3&t){const e=-4&t,s=r/t;for(let r=0;r0&&o(s,s+e,u),a(s+e,s+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,r,u),this._lastRunPath="simd"}else a(0,r,u),this._lastRunPath="scalar";const l=s.outputOffset/4,h=n.slice(l,l+r*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r();function a(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);c.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=u(s);return t(n,e).then(e=>(e&&c.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function o(e){const t=u(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function u(e){const t=new Array(e.length);for(let s=0;s{try{e(h.apply(this,arguments))}catch(e){t(e)}})},c.replaceKernel=function(t){a(e=t,c)},a(e,c),c}}}),ct=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=ht(),g=[l,h,c,f],y=["gpu","cpu"],x={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let b=!0;function v(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){b=!1}static enableValidation(){b=!0}static get isGPUSupported(){return g.some(e=>e.isSupported)}static get isKernelMapSupported(){return g.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return g.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:b,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:b,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:b,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&y.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=v(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),dt=e((e,t)=>{const{GPU:s}=ct(),{alias:c}=pt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=R(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:E}=Se(),{WebGL2Kernel:_}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=N(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:_,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=dt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var N=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,R=function(e,t){this.line=e,this.column=t};R.prototype.offset=function(e){return new R(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new R(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,E.lastIndex=e,e+=E.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;E.lastIndex=this.pos;var e,t=E.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){E.lastIndex=this.pos;var a=E.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return N.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Ee=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",_e=Ee+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:Ee,13:_e,14:_e+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Re(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Ne.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Ne.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Ne.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Ne.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Ne.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Ne.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Ne.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Ne.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Ne.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Re(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Ne(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(n.length),_={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},N=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},R=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:_,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:N,onFunctionCall:R,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),N=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:N}=m(),{GLTextureFloat2D:R}=E(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=N,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=N,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return _}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function _(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const s=u(e,R.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:N}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:N});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=R;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:E}=de(),{WebGLKernelValueArray3:_}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=N(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=R(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=R();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),Ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=Ee(),{WebGL2KernelValueInteger:n}=_e(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Ne(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:E}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:_}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),u|=0,o&&r>0){const t=e[0];if(3&t){const e=-4&t,s=r/t;for(let r=0;r0&&o(s,s+e,u),a(s+e,s+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,r,u),this._lastRunPath="simd"}else a(0,r,u),this._lastRunPath="scalar";const l=s.outputOffset/4,h=n.slice(l,l+r*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);return this.plan||(this.plan=this._buildPlan()),this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:s}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=R(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:E}=Se(),{WebGL2Kernel:_}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=N(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:_,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=ft(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/docs/design/pipeline-compilation.md b/docs/design/pipeline-compilation.md new file mode 100644 index 00000000..2f54a39c --- /dev/null +++ b/docs/design/pipeline-compilation.md @@ -0,0 +1,117 @@ +# Pipeline compilation — design contract (v1) + +Approved API shape. Every implementation decision below is settled; agents +build to this, deviations require a named reason in the final report. + +## API + +```js +const sweep = gpu.createKernel(function (u, src) { ... }, { constants: { hi }, output: [1024, 1024] }); + +const solve = gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; +}, { constants: { sweeps: 512 } }); + +const result = await solve(u0, q); // one launch, fences inside, one readback +``` + +- `gpu.createPipeline(fn, settings?)`; `settings.constants` only in v1. +- The orchestration function runs ONCE, at build time (first call), with + opaque handles for arguments; kernel calls are recorded; JS loops unroll + into a static plan. Later calls execute the compiled plan. +- Calling the pipeline ALWAYS returns a Promise (the async contract). +- Return value: a handle, or an Array/plain object of handles — the call + resolves to the same shape holding plain results. +- Inner kernels do NOT need `pipeline: true`; intermediate residency is the + pipeline's business. Kernels may be shared between pipelines and direct use. +- `this.constants` inside the orchestration fn are trace-time facts. Changing + them = `pipeline.setConstants({...})`, which invalidates the plan and + re-traces on next call (kernels already treat settings this way). + +## Trace-time rules (violations throw AT BUILD, naming the violation) + +- Reading an element / property of a handle → throw + ("pipeline intermediate results cannot be read during orchestration"). +- Using a handle in arithmetic / conditions (valueOf/Symbol.toPrimitive) → throw. +- `Math.random()` during trace → throw (orchestration must be deterministic). +- Only recorded operations: calling gpu.js kernels created by the same GPU + instance with handle/plain-JS-value arguments. Calling anything else that + consumes a handle → throw when the handle escapes detection (best effort: + handles are frozen class instances; document limits). +- Non-handle arguments (numbers, arrays uploaded per call) are legal kernel + args inside the plan; arrays passed to the PIPELINE are uploaded once per + pipeline call; plain values captured during trace are frozen into the plan + (document this: closure-captured mutables freeze at trace, like constants). + +## Plan IR + +`{ steps: [ { kernel, argBindings[], outputBuffer } ], buffers: [...], results }` +- argBinding: `{ source: 'pipelineArg', index }` | `{ source: 'step', step }` | + `{ source: 'literal', value }`. +- Buffer assignment: a step whose kernel instance would overwrite a buffer a + later (or the same) step still reads gets automatic double-buffering + (ping-pong). The classic case — `u = sweep(u, q)` in a loop — must compile + to two alternating buffers with ONE kernel. Liveness is static (plan is a + DAG after unrolling). + +## Execution + +- Generic executor (every backend, correctness reference): execute steps + sequentially through the existing kernel machinery with `pipeline: true` + forced on inner kernel INSTANCES cloned/configured for pipeline use (do not + mutate the user's kernel settings observably); final results read back once. + On GL this is textures end-to-end; on cpu plain arrays; on webgpu buffer + handles. This executor ships for cpu/webgl/webgl2/headlessgl/webgpu in v1. +- webasm fused executor (the point of the feature): all steps compile over + ONE wasm memory laid out `[pipeline args | plan buffers]`; passes run + back-to-back with intermediates never leaving wasm memory (no slice / + flattenTo between steps). Sync path first. Threaded path: workers execute + the whole plan with Atomics-based barriers between steps over the shared + memory (generation counter; no main-thread round trip per pass); falls back + to sync-fused when threads are unavailable, and to the generic executor for + anything the webasm backend cannot take (its usual degradation contract, + with fallbackReason). +- Pipeline call semantics: arguments sampled at call time; concurrent calls + to the same pipeline serialize on a tail like threaded kernels do. +- `pipeline.destroy()` releases plan buffers/instances; gpu.destroy() reaches + pipelines like kernels. + +## v1 exclusions (documented, not silently missing) + +- No `this.check` / mid-plan readback (reserved; design in README as future). +- No webgpu single-command-encoder lowering (generic executor only; noted). +- No graphical kernels inside pipelines (throw with message). +- No kernel maps inside pipelines in v1 (throw with message). +- `toString()` deferred. + +## Files + +- `src/pipeline.js` — tracer, handle, plan IR, generic executor, Pipeline class. +- `src/gpu.js` — `createPipeline` wiring; pipeline registry for destroy. +- `src/backend/web-assembly/pipeline-executor.js` — fused sync + threaded + barrier lowering (worker-pool changes as needed). +- `test/features/pipeline/*.js` — see testing section. +- README section + `src/index.d.ts` declarations. + +## Testing bar + +- Trace violations: each banned operation throws at build with its named message. +- Correctness vs plain-JS references on every available backend: jacobi-like + ping-pong (ONE kernel), multi-kernel chain, multi-output object return, + literal/closure-captured args, pipeline arg reused by several steps. +- Double-buffering: a 3-step chain where step 3 reads step 1's output (not + just the previous step) — liveness must keep it alive. +- setConstants re-trace; destroy; concurrent calls; webasm degradation path. +- The discriminating-test discipline: every behavioral test must fail on a + tree with the feature stubbed out (trivially true) AND the fused executor's + tests must fail if fusion silently falls back to the generic executor + (assert on an executor-identity probe, e.g. `pipeline.executorKind`). + +## Benchmark acceptance + +gauntlet jacobi/heat rewritten via createPipeline must beat their current +per-pass webasm numbers materially (target: ≥1.5× on heat threaded) and match +checksums; numbers reported in the PR. diff --git a/src/gpu.js b/src/gpu.js index 95070e02..c17a361c 100644 --- a/src/gpu.js +++ b/src/gpu.js @@ -8,6 +8,7 @@ const { WebGLKernel } = require('./backend/web-gl/kernel'); const { WebGPUKernel } = require('./backend/web-gpu/kernel'); const { WebAssemblyKernel } = require('./backend/web-assembly/kernel'); const { kernelRunShortcut } = require('./kernel-run-shortcut'); +const { Pipeline } = require('./pipeline'); /** @@ -172,6 +173,7 @@ class GPU { } } this.kernels = []; + this.pipelines = []; this.functions = []; this.nativeFunctions = []; this.injectedNative = null; @@ -572,6 +574,46 @@ class GPU { return kernelRun; } + /** + * @desc Compile a whole multi-kernel computation into one callable plan + * (docs/design/pipeline-compilation.md). The orchestration function runs + * once, at build time, with opaque handles for arguments; the kernel calls + * it makes are recorded and replayed on later calls with intermediates + * kept resident. Calling the pipeline always returns a Promise. + * @param {Function} fn - orchestration function; may only call kernels + * created by this GPU instance + * @param {IPipelineSettings} [settings] - `constants` only in v1 + * @returns {IPipelineRunShortcut} callable pipeline + */ + createPipeline(fn, settings) { + if (typeof fn !== 'function') { + throw new Error('createPipeline requires an orchestration function'); + } + if (this.mode === 'dev') { + throw new Error('createPipeline is not supported in dev mode'); + } + const pipeline = new Pipeline(this, fn, settings); + this.pipelines.push(pipeline); + const shortcut = function() { + return pipeline.call(arguments); + }; + shortcut.pipeline = pipeline; + shortcut.setConstants = function(constants) { + pipeline.setConstants(constants); + return shortcut; + }; + shortcut.destroy = function() { + return pipeline.destroy(); + }; + Object.defineProperty(shortcut, 'executorKind', { + get: () => pipeline.executorKind, + }); + Object.defineProperty(shortcut, 'plan', { + get: () => pipeline.plan, + }); + return shortcut; + } + /** * * Create a super kernel which executes sub kernels @@ -779,6 +821,15 @@ class GPU { // if webGl is created and destroyed in the same run loop. setTimeout(() => { try { + // pipelines release their cloned kernel instances, which splice + // themselves out of this.kernels -- so pipelines go first, then + // the surviving kernels + if (this.pipelines) { + const pipelines = this.pipelines.slice(); + for (let i = 0; i < pipelines.length; i++) { + pipelines[i].destroy(); + } + } // kernel.destroy() splices itself out of this.kernels, so walk a copy: // mutating the list being indexed skipped every other kernel, and left // this.kernels[0] undefined below, which meant a single-kernel GPU diff --git a/src/index.d.ts b/src/index.d.ts index 36afedf4..98174658 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -53,6 +53,14 @@ export class GPU { subKernels: ISubKernelObject, rootKernel: ThreadFunction, settings?: IGPUKernelSettings): (((this: IKernelFunctionThis, ...args: ArgTypes) => IMappedKernelResult) & IKernelMapRunShortcut); + /** + * Compile a whole multi-kernel computation into one callable plan. The + * orchestration function runs once, at build time (first call), with + * opaque handles for arguments; the kernel calls it makes are recorded + * and replayed on later calls with intermediates kept resident. Calling + * the pipeline always returns a Promise. + */ + createPipeline(fn: PipelineFunction, settings?: IPipelineSettings): IPipelineRunShortcut; destroy(): Promise; Kernel: typeof Kernel; mode: string; @@ -387,6 +395,34 @@ export interface IKernelRunShortcut extends IKernelRunShortcutBase { export interface IKernelMapRunShortcut extends IKernelRunShortcutBase< { result: KernelOutput } & { [key in keyof SubKernelType]: KernelOutput }> {} +/** + * Opaque stand-in for an intermediate result during pipeline orchestration. + * Reading elements or properties, or using it in arithmetic or conditions, + * throws at build time; its only legal uses are as a kernel argument and in + * the orchestration function's return value. + */ +export interface IPipelineHandle {} + +export type PipelineFunction = (this: { constants: IConstantsThis }, ...args: IPipelineHandle[]) => + IPipelineHandle | IPipelineHandle[] | { [key: string]: IPipelineHandle }; + +export interface IPipelineSettings { + /** trace-time facts; change via setConstants, which re-traces on the next call */ + constants?: IConstants; +} + +export type PipelineResult = KernelOutput | KernelOutput[] | { [key: string]: KernelOutput }; + +export interface IPipelineRunShortcut { + (...args: KernelVariable[]): Promise; + setConstants(constants: IConstants): this; + destroy(): Promise; + /** 'generic' runs step-by-step through the normal kernel machinery on every backend */ + readonly executorKind: string; + /** the compiled plan IR; null until the first call builds it */ + readonly plan: object | null; +} + export interface IKernelFeatures { isFloatRead: boolean; kernelMap: boolean; diff --git a/src/kernel-run-shortcut.js b/src/kernel-run-shortcut.js index 84195a65..fb4722af 100644 --- a/src/kernel-run-shortcut.js +++ b/src/kernel-run-shortcut.js @@ -1,5 +1,6 @@ const { utils } = require('./utils'); const { Input } = require('./input'); +const { getActiveTrace } = require('./pipeline'); /** * Makes kernels easier for mortals (including me) @@ -162,6 +163,14 @@ function kernelRunShortcut(kernel) { } function run() { + // an open pipeline trace owns every kernel call made under it: the call + // is recorded into the plan and answered with a handle instead of + // executing (src/pipeline.js); traces are synchronous, so no user run + // can be misrecorded + const trace = getActiveTrace(); + if (trace) { + return trace.recordKernelCall(shortcut, arguments); + } if (kernel.constructor.isAsync === true || kernel.asyncMode === true) { return asyncRun(arguments); } diff --git a/src/pipeline.js b/src/pipeline.js new file mode 100644 index 00000000..ca2c9493 --- /dev/null +++ b/src/pipeline.js @@ -0,0 +1,495 @@ +const { Input } = require('./input'); + +/** + * Pipeline compilation (docs/design/pipeline-compilation.md): the + * orchestration function runs ONCE, at build time, against opaque handles; + * every kernel call made while the trace is open is recorded into a static + * plan, and later pipeline calls execute the plan without re-entering user + * code. JS loops in the orchestration therefore unroll at trace time, and + * closure-captured plain values freeze into the plan the same way constants + * do. + */ + +const MSG_HANDLE_READ = 'pipeline intermediate results cannot be read during orchestration'; +const MSG_HANDLE_PRIMITIVE = 'pipeline intermediate results cannot be used in arithmetic or conditions during orchestration'; +const MSG_MATH_RANDOM = 'Math.random() is not allowed during pipeline orchestration; orchestration must be deterministic'; +const MSG_FOREIGN_KERNEL = 'pipelines can only call kernels created by the same GPU instance'; +const MSG_GRAPHICAL = 'graphical kernels are not supported inside pipelines'; +const MSG_KERNEL_MAP = 'kernel maps are not supported inside pipelines'; +const MSG_RETURN_SHAPE = 'a pipeline must return a handle, or an Array or plain object of handles'; +const MSG_FIXED_OUTPUT = 'kernels called inside a pipeline must have a fixed output size'; +const MSG_DESTROYED = 'pipeline has been destroyed'; + +/** + * The class exists for instanceof and for its name in errors; all state + * lives in the trace's WeakMap so the frozen instance has no own properties + * for the Proxy get trap to conflict with. + */ +class PipelineHandle {} + +/** + * Consulted by kernelRunShortcut on every call; non-null only while an + * orchestration function is being traced, which is always synchronous, so a + * module-level slot cannot see two traces at once. + */ +let activeTrace = null; + +function getActiveTrace() { + return activeTrace; +} + +/** + * Trace-time state: records kernel calls as plan steps and mints the opaque + * handles that stand in for values the orchestration never gets to see. + */ +class PipelineTrace { + constructor(gpu) { + this.gpu = gpu; + this.steps = []; + /** + * distinct kernel run-shortcuts, in first-use order; steps refer to them + * by index so the ping-pong loop shape compiles to ONE kernel entry + */ + this.kernels = []; + this.kernelIndexes = new Map(); + this.handleMeta = new WeakMap(); + } + + /** + * @param {Object} meta - {source: 'pipelineArg', index} | {source: 'step', step} + * @returns {Proxy} + */ + createHandle(meta) { + const trace = this; + // the target is frozen and own-property-free, so the get trap may throw + // for every key without violating a Proxy invariant + const target = Object.freeze(new PipelineHandle()); + const handle = new Proxy(target, { + get(_, property) { + if (property === Symbol.toPrimitive || property === 'valueOf' || property === 'toString') { + return () => { + throw new Error(MSG_HANDLE_PRIMITIVE); + }; + } + throw new Error(MSG_HANDLE_READ); + }, + set() { + throw new Error(MSG_HANDLE_READ); + }, + }); + trace.handleMeta.set(handle, meta); + return handle; + } + + /** + * Entry point from kernelRunShortcut while a trace is open: validate the + * kernel, bind the arguments, and answer with a fresh step-output handle + * instead of running anything. + * @param {IKernelRunShortcut} shortcut + * @param {IArguments} args + * @returns {Proxy} + */ + recordKernelCall(shortcut, args) { + const kernel = shortcut.kernel; + if (kernel.gpu !== this.gpu) { + throw new Error(MSG_FOREIGN_KERNEL); + } + if (kernel.graphical) { + throw new Error(MSG_GRAPHICAL); + } + if (kernel.subKernels && kernel.subKernels.length > 0) { + throw new Error(MSG_KERNEL_MAP); + } + if (!kernel.output) { + throw new Error(MSG_FIXED_OUTPUT); + } + let kernelIndex = this.kernelIndexes.get(shortcut); + if (kernelIndex === undefined) { + kernelIndex = this.kernels.length; + this.kernels.push(shortcut); + this.kernelIndexes.set(shortcut, kernelIndex); + } + const argBindings = new Array(args.length); + for (let i = 0; i < args.length; i++) { + argBindings[i] = this.bindValue(args[i]); + } + const stepIndex = this.steps.length; + this.steps.push({ + kernel: kernelIndex, + argBindings, + output: Array.from(kernel.output), + outputBuffer: -1, + }); + return this.createHandle({ source: 'step', step: stepIndex }); + } + + /** + * @returns {Object} argBinding per the plan IR; non-handles snapshot here, + * which is the moment closure-captured mutables freeze + */ + bindValue(value) { + const meta = this.handleMeta.get(value); + if (meta) return meta; + return { source: 'literal', value: snapshotValue(value) }; + } +} + +/** + * Call-time sampling: mutable JS values copy before the call promise can + * yield, so `const p = pipeline(buf); buf[0] = 9;` computes on the value buf + * held at the call. Handles never reach this function -- bindValue checks + * the WeakMap first -- so property access here cannot trip a handle trap. + */ +function snapshotValue(value) { + if (!value || typeof value !== 'object') return value; + // GPU-resident values cannot be mutated from JS between now and the run + if (typeof value.delete === 'function' || typeof value.toArray === 'function') return value; + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(snapshotValue); + if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + return value; +} + +/** + * Static liveness over the unrolled DAG, then greedy slot reuse: a step may + * write a buffer only when the previous occupant's last reader ran strictly + * earlier -- a reader AT the writing step still needs the old contents while + * the new ones are produced, which is exactly what forces `u = sweep(u, q)` + * in a loop onto two alternating buffers. Slots are only shared between + * steps of identical output shape so the fused executor can lay them out as + * fixed regions. + * @param {Array} steps - mutated: outputBuffer assigned per step + * @param {Array} resultBindings + * @returns {Array} buffers + */ +function assignBuffers(steps, resultBindings) { + const lastRead = new Array(steps.length).fill(-1); + for (let i = 0; i < steps.length; i++) { + const bindings = steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === 'step') { + lastRead[binding.step] = Math.max(lastRead[binding.step], i); + } + } + } + for (let i = 0; i < resultBindings.length; i++) { + const binding = resultBindings[i]; + if (binding.source === 'step') { + lastRead[binding.step] = steps.length; + } + } + const buffers = []; + const occupantLastRead = []; + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + let assigned = -1; + for (let b = 0; b < buffers.length; b++) { + if (occupantLastRead[b] < i && sameShape(buffers[b].output, step.output)) { + assigned = b; + break; + } + } + if (assigned === -1) { + assigned = buffers.length; + buffers.push({ output: step.output.slice() }); + occupantLastRead.push(-1); + } + step.outputBuffer = assigned; + occupantLastRead[assigned] = lastRead[i]; + } + return buffers; +} + +function sameShape(a, b) { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +} + +/** + * @param {PipelineTrace} trace + * @param {*} returned - the orchestration function's return value + * @returns {Object} results descriptor {kind, entries: [{key?, binding}]} + */ +function bindResults(trace, returned) { + if (returned === null || returned === undefined) { + throw new Error(MSG_RETURN_SHAPE); + } + if (trace.handleMeta.has(returned)) { + return { kind: 'single', entries: [{ binding: trace.bindValue(returned) }] }; + } + if (Array.isArray(returned)) { + return { + kind: 'array', + entries: returned.map((value, i) => ({ key: i, binding: trace.bindValue(value) })), + }; + } + if (typeof returned === 'object' && !ArrayBuffer.isView(returned)) { + const entries = []; + for (const key in returned) { + if (!returned.hasOwnProperty(key)) continue; + entries.push({ key, binding: trace.bindValue(returned[key]) }); + } + return { kind: 'object', entries }; + } + throw new Error(MSG_RETURN_SHAPE); +} + +class Pipeline { + /** + * @param {GPU} gpu + * @param {Function} fn - orchestration function, run once per (re)trace + * @param {IPipelineSettings} [settings] + */ + constructor(gpu, fn, settings) { + settings = settings || {}; + this.gpu = gpu; + this.fn = fn; + this.argumentCount = fn.length; + this.constants = Object.assign({}, settings.constants || {}); + this.plan = null; + /** + * executor identity probe for tests and later phases: 'generic' executes + * step-by-step through the normal kernel machinery on every backend; the + * webasm fused executors (phase 2) claim their own names + * @type {String} + */ + this.executorKind = 'generic'; + this.destroyed = false; + /** + * concurrent calls to one pipeline serialize on this tail, the same + * contract as threaded webasm kernels + */ + this._tail = Promise.resolve(); + } + + /** + * @desc Always a Promise; arguments sample now, execution queues behind + * any call already in flight. + * @param {IArguments|Array} args + * @returns {Promise<*>} + */ + call(args) { + if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); + const sampled = new Array(args.length); + for (let i = 0; i < args.length; i++) { + sampled[i] = snapshotValue(args[i]); + } + const promise = this._tail.then(() => { + if (this.destroyed) throw new Error(MSG_DESTROYED); + if (!this.plan) { + this.plan = this._buildPlan(); + } + return this._executeGeneric(this.plan, sampled); + }); + this._tail = promise.then(noop, noop); + return promise; + } + + /** + * @desc Trace-time constants change: the plan is invalid, the next call + * re-traces. The release queues behind in-flight calls so their buffers + * are not ripped out from under them. + * @param {Object} constants + * @returns {Pipeline} + */ + setConstants(constants) { + this.constants = Object.assign({}, constants || {}); + const release = () => { + this._releasePlan(); + }; + this._tail = this._tail.then(release, release); + return this; + } + + /** + * @desc Releases plan buffers and cloned kernel instances. Queued calls + * reject; the release itself waits for the call in flight. + * @returns {Promise} + */ + destroy() { + this.destroyed = true; + if (this.gpu && this.gpu.pipelines) { + const index = this.gpu.pipelines.indexOf(this); + if (index !== -1) { + this.gpu.pipelines.splice(index, 1); + } + } + const release = () => { + this._releasePlan(); + }; + const tail = this._tail.then(release, release); + this._tail = tail; + return tail; + } + + /** + * Runs the orchestration function once with handles for arguments; the + * recorded steps become the plan. Math.random is barred for the duration + * because a trace-time draw would freeze into every later call. + * @returns {Object} plan IR + */ + _buildPlan() { + const trace = new PipelineTrace(this.gpu); + const argHandles = new Array(this.argumentCount); + for (let i = 0; i < this.argumentCount; i++) { + argHandles[i] = trace.createHandle({ source: 'pipelineArg', index: i }); + } + const originalRandom = Math.random; + Math.random = function pipelineTraceRandom() { + throw new Error(MSG_MATH_RANDOM); + }; + activeTrace = trace; + let returned; + try { + returned = this.fn.apply({ constants: Object.assign({}, this.constants) }, argHandles); + } finally { + activeTrace = null; + Math.random = originalRandom; + } + const results = bindResults(trace, returned); + const buffers = assignBuffers(trace.steps, results.entries.map(entry => entry.binding)); + const kernels = trace.kernels.map(shortcut => ({ + shortcut, + clone: this._cloneKernel(shortcut), + })); + return { + steps: trace.steps, + buffers, + results, + kernels, + }; + } + + /** + * The plan runs on private instances configured for pipeline use -- + * `pipeline: true, immutable: true` -- so intermediates stay resident + * (textures on GL, fresh arrays on cpu) and the user's kernel settings + * are never observably touched. Kernels stay shared between pipelines and + * direct use through their own shortcuts. + * @param {IKernelRunShortcut} shortcut - the user's kernel + * @returns {IKernelRunShortcut} private clone + */ + _cloneKernel(shortcut) { + const kernel = shortcut.kernel; + const settings = { + output: Array.from(kernel.output), + pipeline: true, + immutable: true, + // argument types can differ between plan positions of one kernel + // (texture in the ping-pong seat, plain array from a pipeline arg) + dynamicArguments: true, + }; + const optional = ['constants', 'constantTypes', 'precision', 'loopMaxIterations', 'strictIntegers', 'fixIntegerDivisionAccuracy', 'optimizeFloatMemory', 'tactic', 'functions', 'nativeFunctions', 'injectedNative', 'debug']; + for (let i = 0; i < optional.length; i++) { + const name = optional[i]; + if (kernel[name] !== null && kernel[name] !== undefined) { + settings[name] = kernel[name]; + } + } + return this.gpu.createKernel(kernel.source, settings); + } + + /** + * The correctness-reference executor: steps run sequentially through the + * cloned kernels, step outputs park in their assigned buffer slot, and + * the final results read back exactly once. Works on every backend; async + * backends are absorbed by awaiting whatever run and readback return. + * @param {Object} plan + * @param {Array} args - sampled pipeline arguments + * @returns {Promise<*>} + */ + async _executeGeneric(plan, args) { + const slots = new Array(plan.buffers.length).fill(null); + try { + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const bindings = step.argBindings; + const resolved = new Array(bindings.length); + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === 'pipelineArg') { + resolved[j] = args[binding.index]; + } else if (binding.source === 'step') { + resolved[j] = slots[plan.steps[binding.step].outputBuffer]; + } else { + resolved[j] = binding.value; + } + } + let output = plan.kernels[step.kernel].clone.apply(null, resolved); + if (output && typeof output.then === 'function') { + output = await output; + } + // the slot's previous occupant is past its last read (assignBuffers + // guarantees it), so its texture can go before the new one parks + releaseValue(slots[step.outputBuffer]); + slots[step.outputBuffer] = output; + } + const results = plan.results; + const values = new Array(results.entries.length); + for (let i = 0; i < results.entries.length; i++) { + const binding = results.entries[i].binding; + let value; + if (binding.source === 'pipelineArg') { + value = args[binding.index]; + } else if (binding.source === 'step') { + value = slots[plan.steps[binding.step].outputBuffer]; + } else { + value = binding.value; + } + if (value && typeof value.toArray === 'function') { + value = value.toArray(); + if (value && typeof value.then === 'function') { + value = await value; + } + } + values[i] = value; + } + if (results.kind === 'single') return values[0]; + if (results.kind === 'array') return values; + const shaped = {}; + for (let i = 0; i < results.entries.length; i++) { + shaped[results.entries[i].key] = values[i]; + } + return shaped; + } finally { + for (let i = 0; i < slots.length; i++) { + releaseValue(slots[i]); + } + } + } + + _releasePlan() { + if (!this.plan) return; + const kernels = this.plan.kernels; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < kernels.length; i++) { + const clone = kernels[i].clone; + // gpu.destroy() may have reached the clone through gpu.kernels before + // this queued release runs; the GL destroy is not re-entrant (its + // splice would eat an unrelated kernel on indexOf -1), so only clones + // still registered are destroyed here + if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) { + clone.destroy(); + } + } + this.plan = null; + } +} + +function releaseValue(value) { + if (value && typeof value.delete === 'function') { + value.delete(); + } +} + +function noop() {} + +module.exports = { + Pipeline, + PipelineHandle, + getActiveTrace, +}; \ No newline at end of file diff --git a/test/all.html b/test/all.html index 7c5b3c9a..d6ccb22e 100644 --- a/test/all.html +++ b/test/all.html @@ -307,6 +307,10 @@ + + + + diff --git a/test/features/pipeline/buffers.js b/test/features/pipeline/buffers.js new file mode 100644 index 00000000..fd78cc9a --- /dev/null +++ b/test/features/pipeline/buffers.js @@ -0,0 +1,106 @@ +const { assert, skip, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline buffers'); + +// Buffer assignment is computed at trace time from static liveness, so the +// plan structure is asserted directly (the plan is exposed for exactly this +// and for later fused executors), with numeric proof alongside where the +// wrong assignment would corrupt values. + +test('ping-pong loop compiles to ONE kernel and two alternating buffers', async assert => { + const gpu = new GPU({ mode: 'cpu' }); + const sweep = gpu.createKernel(function (u, q) { + return u[this.thread.x] * 0.5 + q[this.thread.x]; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 5 } }); + await solve([1, 2, 3, 4], [1, 1, 1, 1]); + + const plan = solve.plan; + assert.equal(plan.kernels.length, 1, 'one kernel entry despite five recorded calls'); + assert.equal(plan.steps.length, 5, 'the JS loop unrolled into five steps'); + assert.equal(plan.buffers.length, 2, 'two buffers, not five'); + assert.deepEqual(plan.steps.map(step => step.outputBuffer), [0, 1, 0, 1, 0], 'slots alternate'); + assert.deepEqual(plan.steps[0].argBindings, [ + { source: 'pipelineArg', index: 0 }, + { source: 'pipelineArg', index: 1 }, + ], 'first step reads the pipeline args'); + assert.deepEqual(plan.steps[1].argBindings[0], { source: 'step', step: 0 }, 'later steps read the previous step'); + gpu.destroy(); +}); + +test('a linear chain reuses slots instead of allocating per step', async assert => { + const gpu = new GPU({ mode: 'cpu' }); + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + return inc(inc(inc(inc(u)))); + }); + await solve([0, 0, 0, 0]); + assert.equal(solve.plan.steps.length, 4); + assert.equal(solve.plan.buffers.length, 2, 'four steps ping-pong over two slots'); + gpu.destroy(); +}); + +function livenessKeepsEarlyOutputAlive(mode) { + return async assert => { + // step 3 reads step 1's output, not just the previous step: if the + // middle step's write reused step 1's slot the final values would be + // built from clobbered data + const gpu = new GPU({ mode }); + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const dbl = gpu.createKernel(function (u) { + return u[this.thread.x] * 2; + }, { output: [4] }); + const mix = gpu.createKernel(function (a, b) { + return a[this.thread.x] * 100 + b[this.thread.x]; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + const a = inc(u); + const b = dbl(a); + return mix(b, a); + }); + + const result = await solve([1, 2, 3, 4]); + // a = u+1, b = 2a, result = 100b + a + assert.deepEqual(Array.from(result), [402, 603, 804, 1005], 'step 1 output survived to step 3'); + const plan = solve.plan; + assert.equal(plan.buffers.length, 3, 'step 1 output kept alive in its own slot'); + assert.notEqual(plan.steps[1].outputBuffer, plan.steps[0].outputBuffer, 'the middle step did not overwrite it'); + gpu.destroy(); + }; +} + +test('liveness keeps a non-adjacent output alive cpu', livenessKeepsEarlyOutputAlive('cpu')); +test('liveness keeps a non-adjacent output alive webasm', livenessKeepsEarlyOutputAlive('webasm')); +(GPU.isHeadlessGLSupported ? test : skip)('liveness keeps a non-adjacent output alive headlessgl', livenessKeepsEarlyOutputAlive('headlessgl')); + +test('slots are only shared between steps of identical output shape', async assert => { + const gpu = new GPU({ mode: 'cpu' }); + const wide = gpu.createKernel(function (u) { + return u[this.thread.x % 4] + 1; + }, { output: [8] }); + const narrow = gpu.createKernel(function (u) { + return u[this.thread.x] + u[this.thread.x + 4]; + }, { output: [4] }); + const wideAgain = gpu.createKernel(function (u) { + return u[this.thread.x % 4] * 2; + }, { output: [8] }); + const solve = gpu.createPipeline(function (u) { + return wideAgain(narrow(wide(u))); + }); + await solve([1, 2, 3, 4]); + const plan = solve.plan; + assert.equal(plan.buffers.length, 2, 'the [4] step cannot share the [8] slot; the last [8] step can'); + assert.equal(plan.steps[2].outputBuffer, plan.steps[0].outputBuffer, 'shape-matched slot reused'); + assert.deepEqual(plan.buffers.map(buffer => buffer.output), [[8], [4]]); + gpu.destroy(); +}); diff --git a/test/features/pipeline/correctness.js b/test/features/pipeline/correctness.js new file mode 100644 index 00000000..f65bea51 --- /dev/null +++ b/test/features/pipeline/correctness.js @@ -0,0 +1,171 @@ +const { assert, skip, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline correctness'); + +// Every scenario runs against a plain-JS reference on every backend +// available here (cpu, webasm, and headlessgl where supported), through the +// generic executor -- asserted by executorKind so a later fused executor +// cannot silently take these tests over. + +function assertClose(assert, actual, expected, label) { + const values = Array.from(actual); + assert.equal(values.length, expected.length, `${ label }: length`); + for (let i = 0; i < values.length; i++) { + const delta = Math.abs(values[i] - expected[i]); + const scale = Math.max(Math.abs(expected[i]), 1); + assert.ok(delta / scale <= 1e-5, `${ label } cell ${ i }: ${ values[i] } vs ${ expected[i] }`); + } +} + +function eachMode(name, body) { + test(`${ name } cpu`, assert => body(assert, 'cpu')); + test(`${ name } webasm`, assert => body(assert, 'webasm')); + (GPU.isHeadlessGLSupported ? test : skip)(`${ name } headlessgl`, assert => body(assert, 'headlessgl')); +} + +eachMode('jacobi-like ping-pong through one kernel', async (assert, mode) => { + const gpu = new GPU({ mode }); + const sweep = gpu.createKernel(function (u, q) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + let right = this.thread.x + 1; + if (right > 7) right = 7; + return 0.25 * (u[left] + u[right]) + q[this.thread.x]; + }, { output: [8] }); + const solve = gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 6 } }); + + const u0 = [0, 1, 2, 3, 4, 5, 6, 7]; + const q = [1, 0.5, 1, 0.5, 1, 0.5, 1, 0.5]; + const result = await solve(u0, q); + + let expected = u0.slice(); + for (let s = 0; s < 6; s++) { + expected = expected.map((_, x) => 0.25 * (expected[Math.max(x - 1, 0)] + expected[Math.min(x + 1, 7)]) + q[x]); + } + assert.equal(solve.executorKind, 'generic', 'phase 1 runs the generic executor'); + assertClose(assert, result, expected, 'jacobi'); + gpu.destroy(); +}); + +eachMode('multi-kernel chain', async (assert, mode) => { + const gpu = new GPU({ mode }); + const double = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [6] }); + const addOne = gpu.createKernel(function (a) { + return a[this.thread.x] + 1; + }, { output: [6] }); + const mix = gpu.createKernel(function (a, b) { + return a[this.thread.x] * b[this.thread.x]; + }, { output: [6] }); + const chain = gpu.createPipeline(function (x) { + const a = double(x); + const b = addOne(a); + return mix(b, a); + }); + + const x = [1, 2, 3, 4, 5, 6]; + const result = await chain(x); + const expected = x.map(v => (v * 2 + 1) * (v * 2)); + assert.equal(chain.executorKind, 'generic'); + assertClose(assert, result, expected, 'chain'); + gpu.destroy(); +}); + +eachMode('multi-output object return', async (assert, mode) => { + const gpu = new GPU({ mode }); + const double = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4] }); + const negate = gpu.createKernel(function (a) { + return -a[this.thread.x]; + }, { output: [4] }); + const both = gpu.createPipeline(function (x) { + return { + doubled: double(x), + negated: negate(x), + }; + }); + + const x = [1, 2, 3, 4]; + const result = await both(x); + assert.deepEqual(Object.keys(result).sort(), ['doubled', 'negated'], 'resolves to the same object shape'); + assertClose(assert, result.doubled, [2, 4, 6, 8], 'doubled'); + assertClose(assert, result.negated, [-1, -2, -3, -4], 'negated'); + gpu.destroy(); +}); + +eachMode('array return resolves to an array of plain results', async (assert, mode) => { + const gpu = new GPU({ mode }); + const double = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4] }); + const pair = gpu.createPipeline(function (x) { + const once = double(x); + return [once, double(once)]; + }); + const result = await pair([1, 2, 3, 4]); + assert.equal(result.length, 2); + assertClose(assert, result[0], [2, 4, 6, 8], 'first'); + assertClose(assert, result[1], [4, 8, 12, 16], 'second'); + gpu.destroy(); +}); + +eachMode('literal and closure-captured kernel arguments', async (assert, mode) => { + const gpu = new GPU({ mode }); + const scale = gpu.createKernel(function (a, k) { + return a[this.thread.x] * k; + }, { output: [4] }); + const offset = gpu.createKernel(function (a, o) { + return a[this.thread.x] + o[this.thread.x]; + }, { output: [4] }); + const captured = [10, 20, 30, 40]; + const solve = gpu.createPipeline(function (x) { + return offset(scale(x, 3), captured); + }); + + const result = await solve([1, 2, 3, 4]); + assertClose(assert, result, [13, 26, 39, 52], 'literal scalar and captured array'); + gpu.destroy(); +}); + +eachMode('pipeline arg reused by several steps', async (assert, mode) => { + const gpu = new GPU({ mode }); + const add = gpu.createKernel(function (a, b) { + return a[this.thread.x] + b[this.thread.x]; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u, q) { + const a = add(u, q); + const b = add(a, q); + return add(b, q); + }); + + const result = await solve([1, 2, 3, 4], [10, 10, 10, 10]); + assertClose(assert, result, [31, 32, 33, 34], 'q consumed by three steps'); + gpu.destroy(); +}); + +eachMode('2d output kernels', async (assert, mode) => { + const gpu = new GPU({ mode }); + const grow = gpu.createKernel(function (m) { + return m[this.thread.y][this.thread.x] + 1; + }, { output: [3, 2] }); + const solve = gpu.createPipeline(function (m) { + for (let i = 0; i < this.constants.passes; i++) { + m = grow(m); + } + return m; + }, { constants: { passes: 3 } }); + + const result = await solve([[0, 1, 2], [10, 11, 12]]); + assert.equal(result.length, 2, '2d shape survives readback'); + assertClose(assert, result[0], [3, 4, 5], 'row 0'); + assertClose(assert, result[1], [13, 14, 15], 'row 1'); + gpu.destroy(); +}); diff --git a/test/features/pipeline/lifecycle.js b/test/features/pipeline/lifecycle.js new file mode 100644 index 00000000..bf98c306 --- /dev/null +++ b/test/features/pipeline/lifecycle.js @@ -0,0 +1,207 @@ +const { assert, skip, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline lifecycle'); + +function makeSolver(mode, sweeps) { + const gpu = new GPU({ mode }); + let traceCount = 0; + const sweep = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + traceCount++; + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u); + } + return u; + }, { constants: { sweeps } }); + return { gpu, solve, traces: () => traceCount }; +} + +test('calling a pipeline always returns a Promise', assert => { + const { gpu, solve } = makeSolver('cpu', 2); + const promise = solve([1, 2, 3, 4]); + assert.ok(promise instanceof Promise); + return promise.then(() => gpu.destroy()); +}); + +test('the orchestration function runs once, at the first call', async assert => { + const { gpu, solve, traces } = makeSolver('cpu', 2); + assert.equal(traces(), 0, 'not traced at createPipeline'); + assert.deepEqual(Array.from(await solve([1, 2, 3, 4])), [3, 4, 5, 6]); + assert.equal(traces(), 1, 'traced at the first call'); + assert.deepEqual(Array.from(await solve([5, 6, 7, 8])), [7, 8, 9, 10]); + assert.equal(traces(), 1, 'later calls replay the plan'); + gpu.destroy(); +}); + +test('setConstants invalidates the plan and re-traces on the next call', async assert => { + const { gpu, solve, traces } = makeSolver('cpu', 2); + assert.deepEqual(Array.from(await solve([0, 0, 0, 0])), [2, 2, 2, 2]); + solve.setConstants({ sweeps: 5 }); + assert.equal(traces(), 1, 'setConstants alone does not trace'); + assert.deepEqual(Array.from(await solve([0, 0, 0, 0])), [5, 5, 5, 5], 'new constants took effect'); + assert.equal(traces(), 2, 're-traced exactly once'); + gpu.destroy(); +}); + +test('closure-captured mutables freeze at trace, like constants', async assert => { + const gpu = new GPU({ mode: 'cpu' }); + const offset = gpu.createKernel(function (u, o) { + return u[this.thread.x] + o[this.thread.x]; + }, { output: [4] }); + const captured = [10, 20, 30, 40]; + const solve = gpu.createPipeline(function (u) { + return offset(u, captured); + }); + assert.deepEqual(Array.from(await solve([1, 1, 1, 1])), [11, 21, 31, 41]); + captured[0] = 9999; + assert.deepEqual(Array.from(await solve([1, 1, 1, 1])), [11, 21, 31, 41], 'trace-time value survives the mutation'); + gpu.destroy(); +}); + +test('pipeline arguments are sampled at call time', async assert => { + const { gpu, solve } = makeSolver('cpu', 1); + const input = new Float32Array([1, 2, 3, 4]); + const promise = solve(input); + input[0] = 9999; + assert.deepEqual(Array.from(await promise), [2, 3, 4, 5], 'mutation after the call is not observed'); + gpu.destroy(); +}); + +test('concurrent calls serialize and both resolve correctly', async assert => { + const { gpu, solve, traces } = makeSolver('cpu', 3); + const first = solve([0, 0, 0, 0]); + const second = solve([10, 10, 10, 10]); + const results = await Promise.all([first, second]); + assert.deepEqual(Array.from(results[0]), [3, 3, 3, 3]); + assert.deepEqual(Array.from(results[1]), [13, 13, 13, 13]); + assert.equal(traces(), 1, 'the build ran once even with a call queued behind it'); + gpu.destroy(); +}); + +test('destroy releases the pipeline; later calls reject', async assert => { + const { gpu, solve } = makeSolver('cpu', 2); + await solve([1, 2, 3, 4]); + await solve.destroy(); + assert.equal(solve.plan, null, 'plan released'); + await assert.rejects(solve([1, 2, 3, 4]), /pipeline has been destroyed/); + await solve.destroy(); + assert.ok(true, 'double destroy tolerated'); + gpu.destroy(); +}); + +test('gpu.destroy reaches pipelines', async assert => { + const { gpu, solve } = makeSolver('cpu', 2); + await solve([1, 2, 3, 4]); + assert.equal(gpu.pipelines.length, 1, 'pipeline registered on the gpu'); + await gpu.destroy(); + assert.equal(gpu.pipelines.length, 0, 'registry emptied'); + await assert.rejects(solve([1, 2, 3, 4]), /pipeline has been destroyed/); +}); + +test('the user kernel is not observably reconfigured by pipeline use', async assert => { + const { gpu, solve } = makeSolver('cpu', 2); + const direct = gpu.createKernel(function (u) { + return u[this.thread.x] * 2; + }, { output: [4] }); + const combined = gpu.createPipeline(function (u) { + return direct(u); + }); + await combined([1, 2, 3, 4]); + assert.equal(direct.pipeline, false, 'pipeline flag untouched'); + assert.equal(direct.immutable, false, 'immutable flag untouched'); + const plain = direct([1, 2, 3, 4]); + assert.ok(plain instanceof Float32Array, 'direct call still renders a plain array'); + assert.deepEqual(Array.from(plain), [2, 4, 6, 8]); + await solve([1, 2, 3, 4]); + gpu.destroy(); +}); + +(GPU.isHeadlessGLSupported ? test : skip)('destroy releases GL textures without breaking the shared context', async assert => { + const gpu = new GPU({ mode: 'headlessgl' }); + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + return inc(inc(u)); + }); + assert.deepEqual(Array.from(await solve([1, 2, 3, 4])), [3, 4, 5, 6]); + await solve.destroy(); + // the user's kernel shares the context the pipeline's clones just left + assert.deepEqual(Array.from(inc([1, 2, 3, 4])), [2, 3, 4, 5], 'context survives the pipeline teardown'); + gpu.destroy(); +}); + +(GPU.isHeadlessGLSupported ? test : skip)('intermediates stay resident: one readback per call headlessgl', async assert => { + // the generic executor keeps step outputs as textures end-to-end; only + // the final result crosses back to JS, so gl.readPixels must fire exactly + // once per pipeline call no matter how many steps ran + const gpu = new GPU({ mode: 'headlessgl' }); + const sweep = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [8] }); + const solve = gpu.createPipeline(function (u) { + for (let s = 0; s < 6; s++) { + u = sweep(u); + } + return u; + }); + await solve([0, 0, 0, 0, 0, 0, 0, 0]); + const gl = gpu.context; + let readbacks = 0; + const originalReadPixels = gl.readPixels.bind(gl); + gl.readPixels = function() { + readbacks++; + return originalReadPixels.apply(this, arguments); + }; + const result = await solve([1, 1, 1, 1, 1, 1, 1, 1]); + gl.readPixels = originalReadPixels; + assert.deepEqual(Array.from(result), [7, 7, 7, 7, 7, 7, 7, 7]); + assert.equal(readbacks, 1, 'six steps, one readback'); + gpu.destroy(); +}); + +(GPU.isHeadlessGLSupported ? test : skip)('repeated calls do not accumulate textures headlessgl', async assert => { + // the executor parks step outputs in plan buffer slots and releases the + // previous occupant; per-call texture population must therefore be flat + const gpu = new GPU({ mode: 'headlessgl' }); + const sweep = gpu.createKernel(function (u) { + return u[this.thread.x] * 0.5 + 1; + }, { output: [16] }); + const solve = gpu.createPipeline(function (u) { + for (let s = 0; s < 8; s++) { + u = sweep(u); + } + return u; + }); + const input = new Float32Array(16).fill(1); + await solve(input); + // GL textures are raw context handles behind refcounts, so the context is + // the only honest census: a slot occupant dropped without release leaks + // its handle forever (net > 0), and a plan that fails to ping-pong holds + // every step's output at once (peak ~ steps, not ~ buffers) + const gl = gpu.context; + let live = 0; + let peak = 0; + const originalCreate = gl.createTexture.bind(gl); + const originalDelete = gl.deleteTexture.bind(gl); + gl.createTexture = () => { + live++; + peak = Math.max(peak, live); + return originalCreate(); + }; + gl.deleteTexture = texture => { + live--; + return originalDelete(texture); + }; + for (let i = 0; i < 5; i++) { + await solve(input); + } + gl.createTexture = originalCreate; + gl.deleteTexture = originalDelete; + assert.equal(live, 0, 'no texture handles leaked across 5 calls'); + assert.ok(peak <= 3, `peak live intermediates bounded by the two plan buffers, saw ${ peak }`); + gpu.destroy(); +}); diff --git a/test/features/pipeline/trace-rules.js b/test/features/pipeline/trace-rules.js new file mode 100644 index 00000000..6f859cfb --- /dev/null +++ b/test/features/pipeline/trace-rules.js @@ -0,0 +1,167 @@ +const { assert, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline trace rules'); + +// Trace rules are backend-independent: the orchestration function runs and +// fails before any kernel executes, so cpu mode proves them for every +// backend. The build happens at the FIRST CALL, so violations surface as a +// rejection of that call's promise -- the async contract -- never as a +// synchronous throw from createPipeline. + +function makeGPU() { + const gpu = new GPU({ mode: 'cpu' }); + const sweep = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + return { gpu, sweep }; +} + +test('createPipeline does not run the orchestration function', assert => { + assert.expect(1); + const { gpu } = makeGPU(); + let ran = false; + gpu.createPipeline(function (u) { + ran = true; + return u; + }); + assert.equal(ran, false, 'trace deferred to the first call'); + gpu.destroy(); +}); + +test('reading an element of a handle throws at build', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + const v = sweep(u); + return v[0]; + }); + await assert.rejects(solve([1, 2, 3, 4]), /pipeline intermediate results cannot be read during orchestration/); + gpu.destroy(); +}); + +test('reading a property of a handle throws at build', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + const v = sweep(u); + return v.length; + }); + await assert.rejects(solve([1, 2, 3, 4]), /pipeline intermediate results cannot be read during orchestration/); + gpu.destroy(); +}); + +test('using a handle in arithmetic throws at build', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + const v = sweep(u); + return sweep(v * 2); + }); + await assert.rejects(solve([1, 2, 3, 4]), /cannot be used in arithmetic or conditions during orchestration/); + gpu.destroy(); +}); + +test('using a handle in a condition throws at build', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + const v = sweep(u); + if (v > 0) { + return sweep(v); + } + return v; + }); + await assert.rejects(solve([1, 2, 3, 4]), /cannot be used in arithmetic or conditions during orchestration/); + gpu.destroy(); +}); + +test('Math.random during orchestration throws at build, and is restored after', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + if (Math.random() > 0.5) { + return sweep(u); + } + return sweep(sweep(u)); + }); + await assert.rejects(solve([1, 2, 3, 4]), /Math\.random\(\) is not allowed during pipeline orchestration/); + const draw = Math.random(); + assert.ok(draw >= 0 && draw < 1, 'Math.random restored after the failed trace'); + gpu.destroy(); +}); + +test('calling a kernel from another GPU instance throws at build', async assert => { + const { gpu } = makeGPU(); + const other = new GPU({ mode: 'cpu' }); + const foreign = other.createKernel(function (u) { + return u[this.thread.x] * 2; + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + return foreign(u); + }); + await assert.rejects(solve([1, 2, 3, 4]), /pipelines can only call kernels created by the same GPU instance/); + gpu.destroy(); + other.destroy(); +}); + +test('graphical kernels inside a pipeline throw at build', async assert => { + const { gpu } = makeGPU(); + const draw = gpu.createKernel(function () { + this.color(1, 0, 0, 1); + }, { output: [2, 2], graphical: true }); + const solve = gpu.createPipeline(function (u) { + draw(u); + return u; + }); + await assert.rejects(solve([1, 2, 3, 4]), /graphical kernels are not supported inside pipelines/); + gpu.destroy(); +}); + +test('kernel maps inside a pipeline throw at build', async assert => { + const { gpu } = makeGPU(); + const mapped = gpu.createKernelMap({ + squared: function square(v) { + return v * v; + }, + }, function (u) { + return square(u[this.thread.x]); + }, { output: [4] }); + const solve = gpu.createPipeline(function (u) { + return mapped(u); + }); + await assert.rejects(solve([1, 2, 3, 4]), /kernel maps are not supported inside pipelines/); + gpu.destroy(); +}); + +test('a handle escaping into a non-kernel function still throws when consumed', async assert => { + // best effort per the contract: the escape is caught the moment the + // foreign function touches the handle, not at the call boundary + const { gpu, sweep } = makeGPU(); + function norm(values) { + return Math.abs(values[0]); + } + const solve = gpu.createPipeline(function (u) { + const v = sweep(u); + norm(v); + return v; + }); + await assert.rejects(solve([1, 2, 3, 4]), /pipeline intermediate results cannot be read during orchestration/); + gpu.destroy(); +}); + +test('returning nothing throws at build', async assert => { + const { gpu, sweep } = makeGPU(); + const solve = gpu.createPipeline(function (u) { + sweep(u); + }); + await assert.rejects(solve([1, 2, 3, 4]), /must return a handle, or an Array or plain object of handles/); + gpu.destroy(); +}); + +test('kernels without a fixed output throw at build', async assert => { + const { gpu } = makeGPU(); + const sized = gpu.createKernel(function (u) { + return u[this.thread.x]; + }); + const solve = gpu.createPipeline(function (u) { + return sized(u); + }); + await assert.rejects(solve([1, 2, 3, 4]), /kernels called inside a pipeline must have a fixed output size/); + gpu.destroy(); +}); From 90365c228b556d9c97dbcc83cc8ce31f951b6131 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 13:05:07 +0800 Subject: [PATCH 02/16] =?UTF-8?q?feat:=20pipeline=20compilation=20phase=20?= =?UTF-8?q?2=20=E2=80=94=20webasm=20fused=20sync=20executor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every plan step compiles to a wasm module over one shared memory laid out [pipeline args | literals | constants | plan buffers]; offsets bake per step, so the ping-pong loop lands on two instances of one kernel and intermediates never leave wasm memory between passes. Per call: one flattenTo per array argument, steps back-to-back synchronously, one readback at the end. Module assembly is reused from WebAssemblyKernel: _assembleModule takes an optional layout.totalBytes for the shared extent, and the SIMD row-span dispatch is extracted to a dispatchSpans static shared by kernel.run and the executor. Argument size/type drift recompiles the fused plan; anything the backend cannot take degrades to the generic executor with fallbackReason, exposed on the pipeline shortcut. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 509 +++++++++++++++++- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 509 +++++++++++++++++- dist/gpu-browser.min.js | 4 +- src/backend/web-assembly/kernel.js | 54 +- src/backend/web-assembly/pipeline-executor.js | 500 +++++++++++++++++ src/gpu.js | 3 + src/index.d.ts | 8 +- src/pipeline.js | 88 ++- test/all.html | 1 + test/features/pipeline/correctness.js | 51 +- test/features/pipeline/fused-webasm.js | 402 ++++++++++++++ 12 files changed, 2044 insertions(+), 89 deletions(-) create mode 100644 src/backend/web-assembly/pipeline-executor.js create mode 100644 test/features/pipeline/fused-webasm.js diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 4eed96de..fb74f584 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -18390,6 +18390,24 @@ return "webasm" + (argumentTypes.length > 0 ? ":" + argumentTypes.join(",") : ""); } static destroyContext(context) {} + static dispatchSpans(run, runSimd, cells, sizeX, seed) { + if (!runSimd || cells === 0) { + run(0, cells, seed); + return "scalar"; + } + if ((sizeX & 3) === 0) { + runSimd(0, cells, seed); + return "simd"; + } + const quadSpan = sizeX & -4; + const rows = cells / sizeX; + for (let row = 0; row < rows; row++) { + const base = row * sizeX; + if (quadSpan > 0) runSimd(base, base + quadSpan, seed); + run(base + quadSpan, base + sizeX, seed); + } + return quadSpan > 0 ? "simd+scalar-tail" : "scalar"; + } static nativeFunctionArguments() { throw new Error("WebAssembly backend does not yet support native functions"); } @@ -18594,7 +18612,7 @@ } _assembleModule(layout, cells, shared) { const builder = new WasmModuleBuilder; - const totalBytes = layout.outputOffset + cells * this.componentCount * 4; + const totalBytes = layout.totalBytes || layout.outputOffset + cells * this.componentCount * 4; const initial = Math.ceil(totalBytes / PAGE_BYTES) + 16; const maximum = Math.max(initial, 4096); builder.addMemoryImport(initial, maximum, shared); @@ -18893,25 +18911,7 @@ let seed = 0; if (this.usesRandom) seed = this.randomSeed !== null ? this.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; seed = seed | 0; - if (runSimd && cells > 0) { - const sizeX = threadDim[0]; - if ((sizeX & 3) === 0) { - runSimd(0, cells, seed); - this._lastRunPath = "simd"; - } else { - const quadSpan = sizeX & -4; - const rows = cells / sizeX; - for (let row = 0; row < rows; row++) { - const base = row * sizeX; - if (quadSpan > 0) runSimd(base, base + quadSpan, seed); - run(base + quadSpan, base + sizeX, seed); - } - this._lastRunPath = quadSpan > 0 ? "simd+scalar-tail" : "scalar"; - } - } else { - run(0, cells, seed); - this._lastRunPath = "scalar"; - } + this._lastRunPath = WebAssemblyKernel.dispatchSpans(run, runSimd, cells, threadDim[0], seed); const base = layout.outputOffset / 4; const data = f32.slice(base, base + cells * this.componentCount); return this._shapeOutput(data, Array.from(this.output), this.componentCount); @@ -19063,6 +19063,418 @@ } }; }); + var require_pipeline_executor = __commonJSMin((exports, module) => { + const {utils: utils} = require_utils(); + const {Input: Input} = require_input(); + const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); + const SUPPORTED_VALUE_TYPES = [ "Array", "Input", "Number", "Float", "Integer", "Boolean" ]; + var FusionFallback = class extends Error { + constructor(reason, recompilable) { + super(reason); + this.isFusionFallback = true; + this.recompilable = Boolean(recompilable); + } + }; + function valueDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function scalarMatches(type, value) { + switch (type) { + case "Integer": + return typeof value === "number" && Number.isInteger(value); + + case "Boolean": + return typeof value === "boolean"; + + default: + return typeof value === "number"; + } + } + module.exports = { + WebAssemblyPipelineExecutor: class WebAssemblyPipelineExecutor { + static compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== "webasm") throw new FusionFallback(`pipeline backend is ${kernel.constructor.mode}; the fused executor requires webasm`); + } + if (plan.steps.length === 0) throw new FusionFallback("plan has no kernel steps to fuse"); + const executor = new WebAssemblyPipelineExecutor(pipeline, plan); + executor._compile(args); + return executor; + } + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = "fused-sync"; + this.destroyed = false; + this.memory = null; + this.f32 = null; + this.i32 = null; + this._stepRuns = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this._resultReads = null; + this._extraShortcuts = []; + this._scratch = new Map; + } + _compile(args) { + const plan = this.plan; + const programs = new Map; + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + const stepReps = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ":" + reps.map(value => utils.getVariableType(value, strict)).join(","); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + this._prepareKernel(kernel, reps); + program = { + id: programs.size, + kernel: kernel, + constantRegions: null + }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + stepReps[i] = reps; + } + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step" && stepPrograms[binding.step].kernel.componentCount !== 1) throw new FusionFallback(`a step returning ${stepPrograms[binding.step].kernel.returnType} cannot feed another step in the fused executor`); + } + } + const align16 = value => Math.ceil(value / 16) * 16; + let offset = 0; + const alloc = bytes => { + const at = offset; + offset = align16(offset + bytes); + return at; + }; + const argArrayRegions = new Map; + const argScalarSlots = new Map; + const literalArrayRegions = new Map; + const uploadArrays = []; + const uploadScalars = []; + const bufferPatches = []; + const stepLayouts = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const local = program.kernel.computeLayout(stepReps[i]); + const arrays = {}; + for (const name in local.arrays) { + const record = local.arrays[name]; + const binding = step.argBindings[record.index]; + const relocated = { + index: record.index, + offset: 0, + dims: record.dims, + flatLength: record.flatLength + }; + if (binding.source === "pipelineArg") { + let region = argArrayRegions.get(binding.index); + if (!region) { + region = { + offset: alloc(record.flatLength * 4), + dims: record.dims, + flatLength: record.flatLength + }; + argArrayRegions.set(binding.index, region); + } + relocated.offset = region.offset; + } else if (binding.source === "literal") { + let region = literalArrayRegions.get(binding.value); + if (!region) { + region = { + offset: alloc(record.flatLength * 4) + }; + literalArrayRegions.set(binding.value, region); + uploadArrays.push({ + offset: region.offset, + flatLength: record.flatLength, + value: binding.value + }); + } + relocated.offset = region.offset; + } else bufferPatches.push({ + record: relocated, + buffer: plan.steps[binding.step].outputBuffer + }); + arrays[name] = relocated; + } + const scalars = {}; + for (const name in local.scalars) { + const record = local.scalars[name]; + const binding = step.argBindings[record.index]; + if (binding.source === "pipelineArg") { + const key = binding.index + ":" + record.type; + let slot = argScalarSlots.get(key); + if (!slot) { + slot = { + index: binding.index, + offset: alloc(4), + type: record.type + }; + argScalarSlots.set(key, slot); + } + scalars[name] = { + index: record.index, + offset: slot.offset, + type: record.type + }; + } else if (binding.source === "literal") { + const slotOffset = alloc(4); + uploadScalars.push({ + offset: slotOffset, + type: record.type, + value: binding.value + }); + scalars[name] = { + index: record.index, + offset: slotOffset, + type: record.type + }; + } else throw new FusionFallback("a step output cannot bind to a scalar argument"); + } + if (!program.constantRegions) { + const regions = {}; + for (const name in local.constantArrays) { + const record = local.constantArrays[name]; + regions[name] = { + offset: alloc(record.flatLength * 4), + dims: record.dims, + flatLength: record.flatLength + }; + const value = program.kernel.constants[name]; + uploadArrays.push({ + offset: regions[name].offset, + flatLength: record.flatLength, + value: value + }); + } + program.constantRegions = regions; + } + stepLayouts[i] = { + arrays: arrays, + scalars: scalars + }; + } + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + const bufferRegions = new Array(plan.buffers.length); + for (let b = 0; b < plan.buffers.length; b++) { + const dims = plan.buffers[b].output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + bufferRegions[b] = { + offset: alloc(cells * bufferComponents[b] * 4), + cells: cells + }; + } + for (let i = 0; i < bufferPatches.length; i++) bufferPatches[i].record.offset = bufferRegions[bufferPatches[i].buffer].offset; + const totalBytes = offset; + const moduleCache = new Map; + const stepRuns = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const program = stepPrograms[i]; + const kernel = program.kernel; + const stepLayout = stepLayouts[i]; + const outputOffset = bufferRegions[plan.steps[i].outputBuffer].offset; + const offsets = []; + for (const name of kernel.argumentNames) { + const record = stepLayout.arrays[name] || stepLayout.scalars[name]; + offsets.push(record ? record.offset : -1); + } + const moduleKey = `${program.id}:${offsets.join(",")}>${outputOffset}`; + let compiled = moduleCache.get(moduleKey); + if (!compiled) { + const layout = { + arrays: stepLayout.arrays, + scalars: stepLayout.scalars, + constantArrays: program.constantRegions, + outputOffset: outputOffset, + totalBytes: totalBytes + }; + const cells = bufferRegions[plan.steps[i].outputBuffer].cells; + const assembled = kernel._assembleModule(layout, cells, false); + if (this.memory === null) { + this.memory = new WebAssembly.Memory({ + initial: assembled.initial, + maximum: assembled.maximum + }); + this.f32 = new Float32Array(this.memory.buffer); + this.i32 = new Int32Array(this.memory.buffer); + } + const imports = { + env: { + memory: this.memory + } + }; + for (const name of kernel.usedMathImports) imports.env["math_" + name] = Math[name]; + const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + compiled = { + run: instance.exports.run, + runSimd: instance.exports.run_simd || null + }; + moduleCache.set(moduleKey, compiled); + } + stepRuns[i] = { + run: compiled.run, + runSimd: compiled.runSimd, + cells: bufferRegions[plan.steps[i].outputBuffer].cells, + sizeX: kernel.threadDim[0], + usesRandom: kernel.usesRandom, + randomSeed: kernel.randomSeed + }; + } + for (let i = 0; i < uploadArrays.length; i++) { + const upload = uploadArrays[i]; + utils.flattenTo(upload.value instanceof Input ? upload.value.value : upload.value, this.f32.subarray(upload.offset / 4, upload.offset / 4 + upload.flatLength)); + } + for (let i = 0; i < uploadScalars.length; i++) this._writeScalar(uploadScalars[i], uploadScalars[i].value); + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === "step") { + const stepIndex = binding.step; + const region = bufferRegions[plan.steps[stepIndex].outputBuffer]; + const kernel = stepPrograms[stepIndex].kernel; + return { + kind: "step", + base: region.offset / 4, + count: region.cells * kernel.componentCount, + output: plan.steps[stepIndex].output, + componentCount: kernel.componentCount, + kernel: kernel + }; + } + if (binding.source === "pipelineArg") return { + kind: "arg", + index: binding.index + }; + return { + kind: "literal", + value: binding.value + }; + }); + this._stepRuns = stepRuns; + this._argArrayRegions = argArrayRegions; + this._argScalarSlots = argScalarSlots; + this._scratch = null; + } + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === "pipelineArg") reps[j] = args[binding.index]; else if (binding.source === "literal") reps[j] = binding.value; else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + _prepareKernel(kernel, reps) { + kernel.argumentTypes = null; + kernel.setupConstants(); + kernel.setupArguments(reps); + for (let i = 0; i < kernel.argumentTypes.length; i++) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.argumentTypes[i]) === -1) throw new FusionFallback(`argument "${kernel.argumentNames[i]}" of type ${kernel.argumentTypes[i]} is not supported on the webasm backend`); + for (const name in kernel.constantTypes) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.constantTypes[name]) === -1) throw new FusionFallback(`constant "${name}" of type ${kernel.constantTypes[name]} is not supported on the webasm backend`); + kernel.validateSettings(reps); + const threadDim = kernel.threadDim = Array.from(kernel.output); + while (threadDim.length < 3) threadDim.push(1); + if (!kernel.translateSource()) throw new FusionFallback(`return type ${kernel.returnType} is not supported on the webasm backend`); + } + _checkArguments(args) { + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); + } + for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + } + _writeScalar(slot, value) { + if (slot.type === "Integer") this.i32[slot.offset / 4] = value | 0; else if (slot.type === "Boolean") this.i32[slot.offset / 4] = value ? 1 : 0; else this.f32[slot.offset / 4] = value; + } + execute(args) { + if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + this._checkArguments(args); + const f32 = this.f32; + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + utils.flattenTo(value instanceof Input ? value.value : value, f32.subarray(region.offset / 4, region.offset / 4 + region.flatLength)); + } + for (const slot of this._argScalarSlots.values()) this._writeScalar(slot, args[slot.index]); + const stepRuns = this._stepRuns; + for (let i = 0; i < stepRuns.length; i++) { + const stepRun = stepRuns[i]; + let seed = 0; + if (stepRun.usesRandom) seed = stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + } + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") { + const data = f32.slice(read.base, read.base + read.count); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } + destroy() { + if (this.destroyed) return; + this.destroyed = true; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); + } + this._extraShortcuts = []; + this._stepRuns = null; + this._resultReads = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this.memory = null; + this.f32 = null; + this.i32 = null; + } + }, + FusionFallback: FusionFallback + }; + }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; @@ -19226,6 +19638,9 @@ this.constants = Object.assign({}, settings.constants || {}); this.plan = null; this.executorKind = "generic"; + this.fallbackReason = null; + this._executor = void 0; + this._fusionDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -19235,7 +19650,27 @@ for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); const promise = this._tail.then(() => { if (this.destroyed) throw new Error(MSG_DESTROYED); - if (!this.plan) this.plan = this._buildPlan(); + if (!this.plan) { + this.plan = this._buildPlan(); + this._executor = void 0; + } + if (this._executor === void 0) this._prepareExecutor(sampled); + if (this._executor) try { + return this._executor.execute(sampled); + } catch (e) { + if (!e || !e.isFusionFallback) throw e; + this._dropExecutor(); + if (e.recompilable) { + this._prepareExecutor(sampled); + if (this._executor) try { + return this._executor.execute(sampled); + } catch (e2) { + if (!e2 || !e2.isFusionFallback) throw e2; + this._dropExecutor(); + this._degrade(e2.message); + } + } else this._degrade(e.message); + } return this._executeGeneric(this.plan, sampled); }); this._tail = promise.then(noop, noop); @@ -19296,6 +19731,29 @@ kernels: kernels }; } + _prepareExecutor(args) { + if (this._fusionDisabled) { + this._executor = false; + return; + } + try { + const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor(); + this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); + this.executorKind = this._executor.kind; + this.fallbackReason = null; + } catch (e) { + this._degrade(e && e.message || "fused executor unavailable"); + } + } + _dropExecutor() { + if (this._executor) this._executor.destroy(); + this._executor = void 0; + } + _degrade(reason) { + this._executor = false; + this.executorKind = "generic"; + this.fallbackReason = reason; + } _cloneKernel(shortcut) { const kernel = shortcut.kernel; const settings = { @@ -19349,6 +19807,10 @@ } } _releasePlan() { + if (this._executor) this._executor.destroy(); + this._executor = void 0; + this.executorKind = "generic"; + this.fallbackReason = null; if (!this.plan) return; const kernels = this.plan.kernels; const gpuKernels = this.gpu && this.gpu.kernels; @@ -19849,6 +20311,9 @@ Object.defineProperty(shortcut, "executorKind", { get: () => pipeline.executorKind }); + Object.defineProperty(shortcut, "fallbackReason", { + get: () => pipeline.fallbackReason + }); Object.defineProperty(shortcut, "plan", { get: () => pipeline.plan }); diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 58567938..61d2a931 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:T,leadingReturnStatement:v,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),L=(e,t,r)=>{B.assignArgumentType(e,t,r)},k=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},M=(e,t,r)=>{B.trackFunctionCall(e,t,r)},R=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:k,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:L,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:M,onNestedFunction:R})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=k();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=T(),{GLTextureArray4Float:p}=v(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:M}=w(),{GLTextureFloat3D:R}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=L(),{GLTextureUnsigned:V}=k(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=R,null):this.output[1]>0?(this.TextureConstructor=M,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=R,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=M,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),R=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return v;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:T,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],T(arguments[4]),T(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function T(e){const t=f[e];return t?r+"."+t:e}function v(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:T,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(M.subKernels){if(f){const t=M.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,M)};`)}else p.push(` const result = { result: ${a(e,M)} };`),f=!0;m===M.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,M)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,M.kernelArguments,[],d,c);if(t)return t;const r=u(e,M.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,M=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:T,loopMaxIterations:v,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,tactic:G});let R=[];if(d.setIndent(2),M.build.apply(M,t),R.push(d.toString()),d.reset(),M.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),M.run.apply(M,t),M.renderKernels?M.renderKernels():M.renderOutput&&M.renderOutput(),R.push(" /** start setup uploads for kernel values **/"),M.kernelArguments.forEach(e=>{R.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),R.push(" /** end setup uploads for kernel values **/"),R.push(d.toString()),M.renderOutput===M.renderTexture)if(d.reset(),M.renderKernels){const e=M.renderKernels(),t=d.getContextVariableName(M.texture.texture);R.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=M;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(M)),R.push(" innerKernel.getPixels = getPixels;")),R.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${R.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:T}=oe(),{WebGLKernelValueSingleArray2DI:v}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:L}=me(),{WebGLKernelValueDynamicUnsignedArray:k}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":v,"Array2D(3)":v,"Array2D(4)":v,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=M(),{fragmentShader:l}=R(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],T={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),T[r]=[e[0],e[1]]),this.maxTexSize=T[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,T[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Te=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),ve=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=Le();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=Le(),{WebGL2KernelValueDynamicHTMLImageArray:u}=ke(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Re(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:T}=Ue(),{WebGL2KernelValueSingleArray1DI:v}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:L}=He(),{WebGL2KernelValueArray4:k}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:T,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=Te(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=ve(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},T={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function v(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>v("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=T[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),u|=0,o&&n>0){const t=e[0];if(3&t){const e=-4&t,r=n/t;for(let n=0;n0&&o(r,r+e,u),a(r+e,r+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,n,u),this._lastRunPath="simd"}else a(0,n,u),this._lastRunPath="scalar";const l=r.outputOffset/4,h=s.slice(l,l+n*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);return this.plan||(this.plan=this._buildPlan()),this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=lt();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ct=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ht(),{Pipeline:g}=lt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let T=!0;function v(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){T=!1}static enableValidation(){T=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:T,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:T,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:T,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=v(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),dt=e((e,t)=>{const{GPU:r}=ct(),{alias:c}=pt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:T}=p(),{HeadlessGLKernel:v}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=Te(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:L}=tt(),{WebGPUKernel:k}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:R}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:T,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:v,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:L,WebGPUKernel:k,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:R,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:M()}}});return e((e,t)=>{const r=dt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),L=(e,t,r)=>{B.assignArgumentType(e,t,r)},k=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:k,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:L,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=k();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=L(),{GLTextureUnsigned:V}=k(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:L}=me(),{WebGLKernelValueDynamicUnsignedArray:k}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=Le();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=Le(),{WebGL2KernelValueDynamicHTMLImageArray:u}=ke(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:L}=He(),{WebGL2KernelValueArray4:k}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),o=["Array","Input","Number","Float","Integer","Boolean"];var u=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,c)).join(",");let d=n.get(p);if(!d){let e;if(i[u.kernel]){const t=this.pipeline._cloneKernel(l.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[u.kernel]=!0,e=l.clone.kernel;this._prepareKernel(e,h),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}a[s]=d,o[s]=h}for(let e=0;e{const t=l;return l=(e=>16*Math.ceil(e/16))(l+e),t},c=new Map,p=new Map,d=new Map,f=[],m=[],g=[],y=new Array(t.steps.length);for(let e=0;e${i}`;let l=T.get(u);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:v},o=b[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,o,!1);null===this.memory&&(this.memory=new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Instance(new WebAssembly.Module(h.bytes),c);l={run:p.exports.run,runSimd:p.exports.run_simd||null},T.set(u,l)}S[e]={run:l.run,runSimd:l.runSimd,cells:b[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=b[t.steps[e].outputBuffer],s=a[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=S,this._argArrayRegions=c,this._argScalarSlots=p,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0),a.dispatchSpans(t.run,t.runSimd,t.cells,t.sizeX,0|r)}const i=this.plan.results,o=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:L}=tt(),{WebGPUKernel:k}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:L,WebGPUKernel:k,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index 43cb7196..b651cbd2 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -22587,6 +22587,24 @@ return "webasm" + (argumentTypes.length > 0 ? ":" + argumentTypes.join(",") : ""); } static destroyContext(context) {} + static dispatchSpans(run, runSimd, cells, sizeX, seed) { + if (!runSimd || cells === 0) { + run(0, cells, seed); + return "scalar"; + } + if ((sizeX & 3) === 0) { + runSimd(0, cells, seed); + return "simd"; + } + const quadSpan = sizeX & -4; + const rows = cells / sizeX; + for (let row = 0; row < rows; row++) { + const base = row * sizeX; + if (quadSpan > 0) runSimd(base, base + quadSpan, seed); + run(base + quadSpan, base + sizeX, seed); + } + return quadSpan > 0 ? "simd+scalar-tail" : "scalar"; + } static nativeFunctionArguments() { throw new Error("WebAssembly backend does not yet support native functions"); } @@ -22791,7 +22809,7 @@ } _assembleModule(layout, cells, shared) { const builder = new WasmModuleBuilder; - const totalBytes = layout.outputOffset + cells * this.componentCount * 4; + const totalBytes = layout.totalBytes || layout.outputOffset + cells * this.componentCount * 4; const initial = Math.ceil(totalBytes / PAGE_BYTES) + 16; const maximum = Math.max(initial, 4096); builder.addMemoryImport(initial, maximum, shared); @@ -23090,25 +23108,7 @@ let seed = 0; if (this.usesRandom) seed = this.randomSeed !== null ? this.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; seed = seed | 0; - if (runSimd && cells > 0) { - const sizeX = threadDim[0]; - if ((sizeX & 3) === 0) { - runSimd(0, cells, seed); - this._lastRunPath = "simd"; - } else { - const quadSpan = sizeX & -4; - const rows = cells / sizeX; - for (let row = 0; row < rows; row++) { - const base = row * sizeX; - if (quadSpan > 0) runSimd(base, base + quadSpan, seed); - run(base + quadSpan, base + sizeX, seed); - } - this._lastRunPath = quadSpan > 0 ? "simd+scalar-tail" : "scalar"; - } - } else { - run(0, cells, seed); - this._lastRunPath = "scalar"; - } + this._lastRunPath = WebAssemblyKernel.dispatchSpans(run, runSimd, cells, threadDim[0], seed); const base = layout.outputOffset / 4; const data = f32.slice(base, base + cells * this.componentCount); return this._shapeOutput(data, Array.from(this.output), this.componentCount); @@ -23260,6 +23260,418 @@ } }; }); + var require_pipeline_executor = __commonJSMin((exports, module) => { + const {utils: utils} = require_utils(); + const {Input: Input} = require_input(); + const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); + const SUPPORTED_VALUE_TYPES = [ "Array", "Input", "Number", "Float", "Integer", "Boolean" ]; + var FusionFallback = class extends Error { + constructor(reason, recompilable) { + super(reason); + this.isFusionFallback = true; + this.recompilable = Boolean(recompilable); + } + }; + function valueDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function scalarMatches(type, value) { + switch (type) { + case "Integer": + return typeof value === "number" && Number.isInteger(value); + + case "Boolean": + return typeof value === "boolean"; + + default: + return typeof value === "number"; + } + } + module.exports = { + WebAssemblyPipelineExecutor: class WebAssemblyPipelineExecutor { + static compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== "webasm") throw new FusionFallback(`pipeline backend is ${kernel.constructor.mode}; the fused executor requires webasm`); + } + if (plan.steps.length === 0) throw new FusionFallback("plan has no kernel steps to fuse"); + const executor = new WebAssemblyPipelineExecutor(pipeline, plan); + executor._compile(args); + return executor; + } + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = "fused-sync"; + this.destroyed = false; + this.memory = null; + this.f32 = null; + this.i32 = null; + this._stepRuns = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this._resultReads = null; + this._extraShortcuts = []; + this._scratch = new Map; + } + _compile(args) { + const plan = this.plan; + const programs = new Map; + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + const stepReps = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ":" + reps.map(value => utils.getVariableType(value, strict)).join(","); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + this._prepareKernel(kernel, reps); + program = { + id: programs.size, + kernel: kernel, + constantRegions: null + }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + stepReps[i] = reps; + } + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step" && stepPrograms[binding.step].kernel.componentCount !== 1) throw new FusionFallback(`a step returning ${stepPrograms[binding.step].kernel.returnType} cannot feed another step in the fused executor`); + } + } + const align16 = value => Math.ceil(value / 16) * 16; + let offset = 0; + const alloc = bytes => { + const at = offset; + offset = align16(offset + bytes); + return at; + }; + const argArrayRegions = new Map; + const argScalarSlots = new Map; + const literalArrayRegions = new Map; + const uploadArrays = []; + const uploadScalars = []; + const bufferPatches = []; + const stepLayouts = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const local = program.kernel.computeLayout(stepReps[i]); + const arrays = {}; + for (const name in local.arrays) { + const record = local.arrays[name]; + const binding = step.argBindings[record.index]; + const relocated = { + index: record.index, + offset: 0, + dims: record.dims, + flatLength: record.flatLength + }; + if (binding.source === "pipelineArg") { + let region = argArrayRegions.get(binding.index); + if (!region) { + region = { + offset: alloc(record.flatLength * 4), + dims: record.dims, + flatLength: record.flatLength + }; + argArrayRegions.set(binding.index, region); + } + relocated.offset = region.offset; + } else if (binding.source === "literal") { + let region = literalArrayRegions.get(binding.value); + if (!region) { + region = { + offset: alloc(record.flatLength * 4) + }; + literalArrayRegions.set(binding.value, region); + uploadArrays.push({ + offset: region.offset, + flatLength: record.flatLength, + value: binding.value + }); + } + relocated.offset = region.offset; + } else bufferPatches.push({ + record: relocated, + buffer: plan.steps[binding.step].outputBuffer + }); + arrays[name] = relocated; + } + const scalars = {}; + for (const name in local.scalars) { + const record = local.scalars[name]; + const binding = step.argBindings[record.index]; + if (binding.source === "pipelineArg") { + const key = binding.index + ":" + record.type; + let slot = argScalarSlots.get(key); + if (!slot) { + slot = { + index: binding.index, + offset: alloc(4), + type: record.type + }; + argScalarSlots.set(key, slot); + } + scalars[name] = { + index: record.index, + offset: slot.offset, + type: record.type + }; + } else if (binding.source === "literal") { + const slotOffset = alloc(4); + uploadScalars.push({ + offset: slotOffset, + type: record.type, + value: binding.value + }); + scalars[name] = { + index: record.index, + offset: slotOffset, + type: record.type + }; + } else throw new FusionFallback("a step output cannot bind to a scalar argument"); + } + if (!program.constantRegions) { + const regions = {}; + for (const name in local.constantArrays) { + const record = local.constantArrays[name]; + regions[name] = { + offset: alloc(record.flatLength * 4), + dims: record.dims, + flatLength: record.flatLength + }; + const value = program.kernel.constants[name]; + uploadArrays.push({ + offset: regions[name].offset, + flatLength: record.flatLength, + value: value + }); + } + program.constantRegions = regions; + } + stepLayouts[i] = { + arrays: arrays, + scalars: scalars + }; + } + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + const bufferRegions = new Array(plan.buffers.length); + for (let b = 0; b < plan.buffers.length; b++) { + const dims = plan.buffers[b].output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + bufferRegions[b] = { + offset: alloc(cells * bufferComponents[b] * 4), + cells: cells + }; + } + for (let i = 0; i < bufferPatches.length; i++) bufferPatches[i].record.offset = bufferRegions[bufferPatches[i].buffer].offset; + const totalBytes = offset; + const moduleCache = new Map; + const stepRuns = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const program = stepPrograms[i]; + const kernel = program.kernel; + const stepLayout = stepLayouts[i]; + const outputOffset = bufferRegions[plan.steps[i].outputBuffer].offset; + const offsets = []; + for (const name of kernel.argumentNames) { + const record = stepLayout.arrays[name] || stepLayout.scalars[name]; + offsets.push(record ? record.offset : -1); + } + const moduleKey = `${program.id}:${offsets.join(",")}>${outputOffset}`; + let compiled = moduleCache.get(moduleKey); + if (!compiled) { + const layout = { + arrays: stepLayout.arrays, + scalars: stepLayout.scalars, + constantArrays: program.constantRegions, + outputOffset: outputOffset, + totalBytes: totalBytes + }; + const cells = bufferRegions[plan.steps[i].outputBuffer].cells; + const assembled = kernel._assembleModule(layout, cells, false); + if (this.memory === null) { + this.memory = new WebAssembly.Memory({ + initial: assembled.initial, + maximum: assembled.maximum + }); + this.f32 = new Float32Array(this.memory.buffer); + this.i32 = new Int32Array(this.memory.buffer); + } + const imports = { + env: { + memory: this.memory + } + }; + for (const name of kernel.usedMathImports) imports.env["math_" + name] = Math[name]; + const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + compiled = { + run: instance.exports.run, + runSimd: instance.exports.run_simd || null + }; + moduleCache.set(moduleKey, compiled); + } + stepRuns[i] = { + run: compiled.run, + runSimd: compiled.runSimd, + cells: bufferRegions[plan.steps[i].outputBuffer].cells, + sizeX: kernel.threadDim[0], + usesRandom: kernel.usesRandom, + randomSeed: kernel.randomSeed + }; + } + for (let i = 0; i < uploadArrays.length; i++) { + const upload = uploadArrays[i]; + utils.flattenTo(upload.value instanceof Input ? upload.value.value : upload.value, this.f32.subarray(upload.offset / 4, upload.offset / 4 + upload.flatLength)); + } + for (let i = 0; i < uploadScalars.length; i++) this._writeScalar(uploadScalars[i], uploadScalars[i].value); + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === "step") { + const stepIndex = binding.step; + const region = bufferRegions[plan.steps[stepIndex].outputBuffer]; + const kernel = stepPrograms[stepIndex].kernel; + return { + kind: "step", + base: region.offset / 4, + count: region.cells * kernel.componentCount, + output: plan.steps[stepIndex].output, + componentCount: kernel.componentCount, + kernel: kernel + }; + } + if (binding.source === "pipelineArg") return { + kind: "arg", + index: binding.index + }; + return { + kind: "literal", + value: binding.value + }; + }); + this._stepRuns = stepRuns; + this._argArrayRegions = argArrayRegions; + this._argScalarSlots = argScalarSlots; + this._scratch = null; + } + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === "pipelineArg") reps[j] = args[binding.index]; else if (binding.source === "literal") reps[j] = binding.value; else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + _prepareKernel(kernel, reps) { + kernel.argumentTypes = null; + kernel.setupConstants(); + kernel.setupArguments(reps); + for (let i = 0; i < kernel.argumentTypes.length; i++) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.argumentTypes[i]) === -1) throw new FusionFallback(`argument "${kernel.argumentNames[i]}" of type ${kernel.argumentTypes[i]} is not supported on the webasm backend`); + for (const name in kernel.constantTypes) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.constantTypes[name]) === -1) throw new FusionFallback(`constant "${name}" of type ${kernel.constantTypes[name]} is not supported on the webasm backend`); + kernel.validateSettings(reps); + const threadDim = kernel.threadDim = Array.from(kernel.output); + while (threadDim.length < 3) threadDim.push(1); + if (!kernel.translateSource()) throw new FusionFallback(`return type ${kernel.returnType} is not supported on the webasm backend`); + } + _checkArguments(args) { + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); + } + for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + } + _writeScalar(slot, value) { + if (slot.type === "Integer") this.i32[slot.offset / 4] = value | 0; else if (slot.type === "Boolean") this.i32[slot.offset / 4] = value ? 1 : 0; else this.f32[slot.offset / 4] = value; + } + execute(args) { + if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + this._checkArguments(args); + const f32 = this.f32; + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + utils.flattenTo(value instanceof Input ? value.value : value, f32.subarray(region.offset / 4, region.offset / 4 + region.flatLength)); + } + for (const slot of this._argScalarSlots.values()) this._writeScalar(slot, args[slot.index]); + const stepRuns = this._stepRuns; + for (let i = 0; i < stepRuns.length; i++) { + const stepRun = stepRuns[i]; + let seed = 0; + if (stepRun.usesRandom) seed = stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + } + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") { + const data = f32.slice(read.base, read.base + read.count); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } + destroy() { + if (this.destroyed) return; + this.destroyed = true; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); + } + this._extraShortcuts = []; + this._stepRuns = null; + this._resultReads = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this.memory = null; + this.f32 = null; + this.i32 = null; + } + }, + FusionFallback: FusionFallback + }; + }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; @@ -23423,6 +23835,9 @@ this.constants = Object.assign({}, settings.constants || {}); this.plan = null; this.executorKind = "generic"; + this.fallbackReason = null; + this._executor = void 0; + this._fusionDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -23432,7 +23847,27 @@ for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); const promise = this._tail.then(() => { if (this.destroyed) throw new Error(MSG_DESTROYED); - if (!this.plan) this.plan = this._buildPlan(); + if (!this.plan) { + this.plan = this._buildPlan(); + this._executor = void 0; + } + if (this._executor === void 0) this._prepareExecutor(sampled); + if (this._executor) try { + return this._executor.execute(sampled); + } catch (e) { + if (!e || !e.isFusionFallback) throw e; + this._dropExecutor(); + if (e.recompilable) { + this._prepareExecutor(sampled); + if (this._executor) try { + return this._executor.execute(sampled); + } catch (e2) { + if (!e2 || !e2.isFusionFallback) throw e2; + this._dropExecutor(); + this._degrade(e2.message); + } + } else this._degrade(e.message); + } return this._executeGeneric(this.plan, sampled); }); this._tail = promise.then(noop, noop); @@ -23493,6 +23928,29 @@ kernels: kernels }; } + _prepareExecutor(args) { + if (this._fusionDisabled) { + this._executor = false; + return; + } + try { + const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor(); + this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); + this.executorKind = this._executor.kind; + this.fallbackReason = null; + } catch (e) { + this._degrade(e && e.message || "fused executor unavailable"); + } + } + _dropExecutor() { + if (this._executor) this._executor.destroy(); + this._executor = void 0; + } + _degrade(reason) { + this._executor = false; + this.executorKind = "generic"; + this.fallbackReason = reason; + } _cloneKernel(shortcut) { const kernel = shortcut.kernel; const settings = { @@ -23546,6 +24004,10 @@ } } _releasePlan() { + if (this._executor) this._executor.destroy(); + this._executor = void 0; + this.executorKind = "generic"; + this.fallbackReason = null; if (!this.plan) return; const kernels = this.plan.kernels; const gpuKernels = this.gpu && this.gpu.kernels; @@ -24046,6 +24508,9 @@ Object.defineProperty(shortcut, "executorKind", { get: () => pipeline.executorKind }); + Object.defineProperty(shortcut, "fallbackReason", { + get: () => pipeline.fallbackReason + }); Object.defineProperty(shortcut, "plan", { get: () => pipeline.plan }); diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 215e3384..e061c4cc 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 12:40:32 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var N=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,R=function(e,t){this.line=e,this.column=t};R.prototype.offset=function(e){return new R(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new R(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,E.lastIndex=e,e+=E.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;E.lastIndex=this.pos;var e,t=E.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){E.lastIndex=this.pos;var a=E.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return N.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Ee=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",_e=Ee+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:Ee,13:_e,14:_e+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Re(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Ne.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Ne.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Ne.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Ne.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Ne.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Ne.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Ne.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Ne.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Ne.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Re(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Ne(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(n.length),_={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},N=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},R=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:_,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:N,onFunctionCall:R,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),N=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:N}=m(),{GLTextureFloat2D:R}=E(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=N,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=N,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return _}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function _(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const s=u(e,R.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:N}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:_,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:N});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=R;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:E}=de(),{WebGLKernelValueArray3:_}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":E,"Array(3)":_,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=N(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=R(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=R();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),Ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=Ee(),{WebGL2KernelValueInteger:n}=_e(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Ne(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:E}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:_}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),u|=0,o&&r>0){const t=e[0];if(3&t){const e=-4&t,s=r/t;for(let r=0;r0&&o(s,s+e,u),a(s+e,s+t,u)}this._lastRunPath=e>0?"simd+scalar-tail":"scalar"}else o(0,r,u),this._lastRunPath="simd"}else a(0,r,u),this._lastRunPath="scalar";const l=s.outputOffset/4,h=n.slice(l,l+r*this.componentCount);return this._shapeOutput(h,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);return this.plan||(this.plan=this._buildPlan()),this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:s}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=R(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:E}=Se(),{WebGL2Kernel:_}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=N(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:_,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=ft(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),o=["Array","Input","Number","Float","Integer","Boolean"];var u=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,c)).join(",");let d=r.get(p);if(!d){let e;if(i[u.kernel]){const t=this.pipeline._cloneKernel(l.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[u.kernel]=!0,e=l.clone.kernel;this._prepareKernel(e,h),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}a[n]=d,o[n]=h}for(let e=0;e{const t=l;return l=(e=>16*Math.ceil(e/16))(l+e),t},c=new Map,p=new Map,d=new Map,f=[],m=[],g=[],y=new Array(t.steps.length);for(let e=0;e${i}`;let l=S.get(u);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:v},o=b[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,o,!1);null===this.memory&&(this.memory=new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Instance(new WebAssembly.Module(h.bytes),c);l={run:p.exports.run,runSimd:p.exports.run_simd||null},S.set(u,l)}T[e]={run:l.run,runSimd:l.runSimd,cells:b[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=b[t.steps[e].outputBuffer],n=a[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=T,this._argArrayRegions=c,this._argScalarSlots=p,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),a.dispatchSpans(t.run,t.runSimd,t.cells,t.sizeX,0|s)}const i=this.plan.results,o=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/backend/web-assembly/kernel.js b/src/backend/web-assembly/kernel.js index 48071d16..3ce06a01 100644 --- a/src/backend/web-assembly/kernel.js +++ b/src/backend/web-assembly/kernel.js @@ -103,6 +103,32 @@ class WebAssemblyKernel extends Kernel { static destroyContext(context) {} + /** + * SIMD quads must not cross an x-row (thread.y/z are uniform per quad): + * rows a multiple of 4 wide vectorize in one span, otherwise each row gets + * a vector span plus a scalar epilogue for its remainder cells. Shared with + * the pipeline executor, which drives per-step instances directly. + * @returns {String} the path taken, for _lastRunPath + */ + static dispatchSpans(run, runSimd, cells, sizeX, seed) { + if (!runSimd || cells === 0) { + run(0, cells, seed); + return 'scalar'; + } + if ((sizeX & 3) === 0) { + runSimd(0, cells, seed); + return 'simd'; + } + const quadSpan = sizeX & ~3; + const rows = cells / sizeX; + for (let row = 0; row < rows; row++) { + const base = row * sizeX; + if (quadSpan > 0) runSimd(base, base + quadSpan, seed); + run(base + quadSpan, base + sizeX, seed); + } + return quadSpan > 0 ? 'simd+scalar-tail' : 'scalar'; + } + static nativeFunctionArguments() { throw new Error('WebAssembly backend does not yet support native functions'); } @@ -404,7 +430,10 @@ class WebAssemblyKernel extends Kernel { */ _assembleModule(layout, cells, shared) { const builder = new WasmModuleBuilder(); - const totalBytes = layout.outputOffset + cells * this.componentCount * 4; + // the pipeline executor passes layout.totalBytes: its modules run over + // one shared memory whose extent exceeds this kernel's own regions, and + // every module of a fused plan must declare identical memory limits + const totalBytes = layout.totalBytes || (layout.outputOffset + cells * this.componentCount * 4); const initial = Math.ceil(totalBytes / PAGE_BYTES) + 16; const maximum = Math.max(initial, 4096); builder.addMemoryImport(initial, maximum, shared); @@ -794,28 +823,7 @@ class WebAssemblyKernel extends Kernel { ((Math.random() * 0x100000000) >>> 0); } seed = seed | 0; - // SIMD quads must not cross an x-row (thread.y/z are uniform per quad): - // rows a multiple of 4 wide vectorize in one span, otherwise each row - // gets a vector span plus a scalar epilogue for its remainder cells - if (runSimd && cells > 0) { - const sizeX = threadDim[0]; - if ((sizeX & 3) === 0) { - runSimd(0, cells, seed); - this._lastRunPath = 'simd'; - } else { - const quadSpan = sizeX & ~3; - const rows = cells / sizeX; - for (let row = 0; row < rows; row++) { - const base = row * sizeX; - if (quadSpan > 0) runSimd(base, base + quadSpan, seed); - run(base + quadSpan, base + sizeX, seed); - } - this._lastRunPath = quadSpan > 0 ? 'simd+scalar-tail' : 'scalar'; - } - } else { - run(0, cells, seed); - this._lastRunPath = 'scalar'; - } + this._lastRunPath = WebAssemblyKernel.dispatchSpans(run, runSimd, cells, threadDim[0], seed); const base = layout.outputOffset / 4; const data = f32.slice(base, base + cells * this.componentCount); diff --git a/src/backend/web-assembly/pipeline-executor.js b/src/backend/web-assembly/pipeline-executor.js new file mode 100644 index 00000000..ebbcb85e --- /dev/null +++ b/src/backend/web-assembly/pipeline-executor.js @@ -0,0 +1,500 @@ +const { utils } = require('../../utils'); +const { Input } = require('../../input'); +const { WebAssemblyKernel } = require('./kernel'); + +/** + * Fused pipeline execution (docs/design/pipeline-compilation.md): every plan + * step compiles to a wasm module over ONE shared memory laid out + * `[ pipeline args | literals | constants | plan buffers ]`, with each + * module's input/output offsets baked against that layout. Steps then run + * back-to-back synchronously; intermediates never leave wasm memory between + * passes — per call there is one flattenTo per pipeline argument and one + * readback per result, however many steps the plan unrolls to. + */ + +const SUPPORTED_VALUE_TYPES = ['Array', 'Input', 'Number', 'Float', 'Integer', 'Boolean']; + +/** + * The degradation signal, per the backend's usual contract: the pipeline + * catches it and runs the generic executor with this reason. `recompilable` + * marks argument size/type drift a fresh fused compile can absorb. + */ +class FusionFallback extends Error { + constructor(reason, recompilable) { + super(reason); + this.isFusionFallback = true; + this.recompilable = Boolean(recompilable); + } +} + +function valueDimensions(value) { + const dims = value instanceof Input ? + Array.from(value.size) : + Array.from(utils.getDimensions(value)); + while (dims.length < 3) { + dims.push(1); + } + return dims; +} + +function scalarMatches(type, value) { + switch (type) { + case 'Integer': + return typeof value === 'number' && Number.isInteger(value); + case 'Boolean': + return typeof value === 'boolean'; + default: + return typeof value === 'number'; + } +} + +class WebAssemblyPipelineExecutor { + /** + * @param {Pipeline} pipeline + * @param {Object} plan - phase-1 plan IR; buffer assignment is reused as-is + * @param {Array} args - the first call's sampled arguments; their sizes and + * types bake into the layout, and execute() re-checks them per call + * @returns {WebAssemblyPipelineExecutor} + * @throws {FusionFallback} for anything the webasm backend cannot take + */ + static compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== 'webasm') { + throw new FusionFallback(`pipeline backend is ${ kernel.constructor.mode }; the fused executor requires webasm`); + } + } + if (plan.steps.length === 0) { + throw new FusionFallback('plan has no kernel steps to fuse'); + } + const executor = new WebAssemblyPipelineExecutor(pipeline, plan); + executor._compile(args); + return executor; + } + + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = 'fused-sync'; + this.destroyed = false; + this.memory = null; + this.f32 = null; + this.i32 = null; + this._stepRuns = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this._resultReads = null; + /** + * kernels created for second and later type signatures of one plan + * kernel (the plan clone carries the first); destroyed with the executor + */ + this._extraShortcuts = []; + // representative Float32Arrays for step-output bindings, keyed by flat + // length; compile-time only, released when _compile returns + this._scratch = new Map(); + } + + /** + * A program is a plan kernel prepared for one argument-type signature: + * type inference and bytecode translation ran, but no module was + * instantiated — modules are per step-offset assignment, built below. + */ + _compile(args) { + const plan = this.plan; + const programs = new Map(); + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + const stepReps = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ':' + reps.map(value => utils.getVariableType(value, strict)).join(','); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + this._prepareKernel(kernel, reps); + program = { id: programs.size, kernel, constantRegions: null }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + stepReps[i] = reps; + } + // vec-returning steps pack componentCount values per cell; no supported + // argument type reads that packing back, so only results may consume them + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === 'step' && stepPrograms[binding.step].kernel.componentCount !== 1) { + throw new FusionFallback(`a step returning ${ stepPrograms[binding.step].kernel.returnType } cannot feed another step in the fused executor`); + } + } + } + + const align16 = value => Math.ceil(value / 16) * 16; + let offset = 0; + const alloc = bytes => { + const at = offset; + offset = align16(offset + bytes); + return at; + }; + const argArrayRegions = new Map(); + const argScalarSlots = new Map(); + const literalArrayRegions = new Map(); + const uploadArrays = []; + const uploadScalars = []; + const bufferPatches = []; + const stepLayouts = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const local = program.kernel.computeLayout(stepReps[i]); + const arrays = {}; + for (const name in local.arrays) { + const record = local.arrays[name]; + const binding = step.argBindings[record.index]; + const relocated = { index: record.index, offset: 0, dims: record.dims, flatLength: record.flatLength }; + if (binding.source === 'pipelineArg') { + let region = argArrayRegions.get(binding.index); + if (!region) { + region = { offset: alloc(record.flatLength * 4), dims: record.dims, flatLength: record.flatLength }; + argArrayRegions.set(binding.index, region); + } + relocated.offset = region.offset; + } else if (binding.source === 'literal') { + let region = literalArrayRegions.get(binding.value); + if (!region) { + region = { offset: alloc(record.flatLength * 4) }; + literalArrayRegions.set(binding.value, region); + uploadArrays.push({ offset: region.offset, flatLength: record.flatLength, value: binding.value }); + } + relocated.offset = region.offset; + } else { + // buffer regions size after every program is known; patched below + bufferPatches.push({ record: relocated, buffer: plan.steps[binding.step].outputBuffer }); + } + arrays[name] = relocated; + } + const scalars = {}; + for (const name in local.scalars) { + const record = local.scalars[name]; + const binding = step.argBindings[record.index]; + if (binding.source === 'pipelineArg') { + const key = binding.index + ':' + record.type; + let slot = argScalarSlots.get(key); + if (!slot) { + slot = { index: binding.index, offset: alloc(4), type: record.type }; + argScalarSlots.set(key, slot); + } + scalars[name] = { index: record.index, offset: slot.offset, type: record.type }; + } else if (binding.source === 'literal') { + const slotOffset = alloc(4); + uploadScalars.push({ offset: slotOffset, type: record.type, value: binding.value }); + scalars[name] = { index: record.index, offset: slotOffset, type: record.type }; + } else { + // unreachable by construction: step-output reps are Inputs, so + // inference can never type this position scalar + throw new FusionFallback('a step output cannot bind to a scalar argument'); + } + } + if (!program.constantRegions) { + const regions = {}; + for (const name in local.constantArrays) { + const record = local.constantArrays[name]; + regions[name] = { offset: alloc(record.flatLength * 4), dims: record.dims, flatLength: record.flatLength }; + const value = program.kernel.constants[name]; + uploadArrays.push({ offset: regions[name].offset, flatLength: record.flatLength, value }); + } + program.constantRegions = regions; + } + stepLayouts[i] = { arrays, scalars }; + } + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + const bufferRegions = new Array(plan.buffers.length); + for (let b = 0; b < plan.buffers.length; b++) { + const dims = plan.buffers[b].output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + bufferRegions[b] = { offset: alloc(cells * bufferComponents[b] * 4), cells }; + } + for (let i = 0; i < bufferPatches.length; i++) { + bufferPatches[i].record.offset = bufferRegions[bufferPatches[i].buffer].offset; + } + const totalBytes = offset; + + // one module per distinct (program, offset assignment): the ping-pong + // loop lands on two instances however many steps it unrolled to + const moduleCache = new Map(); + const stepRuns = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const program = stepPrograms[i]; + const kernel = program.kernel; + const stepLayout = stepLayouts[i]; + const outputOffset = bufferRegions[plan.steps[i].outputBuffer].offset; + const offsets = []; + for (const name of kernel.argumentNames) { + const record = stepLayout.arrays[name] || stepLayout.scalars[name]; + offsets.push(record ? record.offset : -1); + } + const moduleKey = `${ program.id }:${ offsets.join(',') }>${ outputOffset }`; + let compiled = moduleCache.get(moduleKey); + if (!compiled) { + const layout = { + arrays: stepLayout.arrays, + scalars: stepLayout.scalars, + constantArrays: program.constantRegions, + outputOffset, + totalBytes, + }; + const cells = bufferRegions[plan.steps[i].outputBuffer].cells; + const assembled = kernel._assembleModule(layout, cells, false); + if (this.memory === null) { + this.memory = new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum }); + this.f32 = new Float32Array(this.memory.buffer); + this.i32 = new Int32Array(this.memory.buffer); + } + const imports = { env: { memory: this.memory } }; + for (const name of kernel.usedMathImports) { + imports.env['math_' + name] = Math[name]; + } + const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + compiled = { + run: instance.exports.run, + runSimd: instance.exports.run_simd || null, + }; + moduleCache.set(moduleKey, compiled); + } + stepRuns[i] = { + run: compiled.run, + runSimd: compiled.runSimd, + cells: bufferRegions[plan.steps[i].outputBuffer].cells, + sizeX: kernel.threadDim[0], + usesRandom: kernel.usesRandom, + randomSeed: kernel.randomSeed, + }; + } + for (let i = 0; i < uploadArrays.length; i++) { + const upload = uploadArrays[i]; + utils.flattenTo( + upload.value instanceof Input ? upload.value.value : upload.value, + this.f32.subarray(upload.offset / 4, upload.offset / 4 + upload.flatLength) + ); + } + for (let i = 0; i < uploadScalars.length; i++) { + this._writeScalar(uploadScalars[i], uploadScalars[i].value); + } + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === 'step') { + const stepIndex = binding.step; + const region = bufferRegions[plan.steps[stepIndex].outputBuffer]; + const kernel = stepPrograms[stepIndex].kernel; + return { + kind: 'step', + base: region.offset / 4, + count: region.cells * kernel.componentCount, + output: plan.steps[stepIndex].output, + componentCount: kernel.componentCount, + kernel, + }; + } + if (binding.source === 'pipelineArg') { + return { kind: 'arg', index: binding.index }; + } + return { kind: 'literal', value: binding.value }; + }); + this._stepRuns = stepRuns; + this._argArrayRegions = argArrayRegions; + this._argScalarSlots = argScalarSlots; + this._scratch = null; + } + + /** + * Stand-ins with the exact types and dims each binding will have at run + * time, for setupArguments/computeLayout: sampled values stand for + * themselves, a step output becomes an Input over its producer's dims. + */ + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === 'pipelineArg') { + reps[j] = args[binding.index]; + } else if (binding.source === 'literal') { + reps[j] = binding.value; + } else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + + /** + * The analysis half of WebAssemblyKernel.build() without instantiation: + * modules are assembled against the shared layout instead. Inference is + * reset first — on a fused recompile the same kernel must re-infer for the + * new signature, not keep the old one. + */ + _prepareKernel(kernel, reps) { + kernel.argumentTypes = null; + kernel.setupConstants(); + kernel.setupArguments(reps); + for (let i = 0; i < kernel.argumentTypes.length; i++) { + if (SUPPORTED_VALUE_TYPES.indexOf(kernel.argumentTypes[i]) === -1) { + throw new FusionFallback(`argument "${ kernel.argumentNames[i] }" of type ${ kernel.argumentTypes[i] } is not supported on the webasm backend`); + } + } + for (const name in kernel.constantTypes) { + if (SUPPORTED_VALUE_TYPES.indexOf(kernel.constantTypes[name]) === -1) { + throw new FusionFallback(`constant "${ name }" of type ${ kernel.constantTypes[name] } is not supported on the webasm backend`); + } + } + kernel.validateSettings(reps); + const threadDim = kernel.threadDim = Array.from(kernel.output); + while (threadDim.length < 3) { + threadDim.push(1); + } + if (!kernel.translateSource()) { + throw new FusionFallback(`return type ${ kernel.returnType } is not supported on the webasm backend`); + } + } + + /** + * The layout baked argument sizes and scalar types; a call that drifts + * from them throws recompilable so the pipeline compiles a fresh fused + * plan for the new signature, the way the kernel itself re-instantiates + * per size signature. + */ + _checkArguments(args) { + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + if (!value || typeof value !== 'object') { + throw new FusionFallback(`pipeline argument ${ index } is no longer an array`, true); + } + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) { + throw new FusionFallback(`pipeline argument ${ index } changed size from [${ region.dims.join(', ') }] to [${ dims.join(', ') }]`, true); + } + } + for (const slot of this._argScalarSlots.values()) { + if (!scalarMatches(slot.type, args[slot.index])) { + throw new FusionFallback(`pipeline argument ${ slot.index } is no longer of type ${ slot.type }`, true); + } + } + } + + _writeScalar(slot, value) { + if (slot.type === 'Integer') { + this.i32[slot.offset / 4] = value | 0; + } else if (slot.type === 'Boolean') { + this.i32[slot.offset / 4] = value ? 1 : 0; + } else { + this.f32[slot.offset / 4] = value; + } + } + + /** + * @param {Array} args - sampled pipeline arguments + * @returns {*} results shaped per the plan; synchronous — the pipeline's + * tail promise provides the async contract + */ + execute(args) { + if (this.destroyed) { + throw new Error('pipeline fused executor has been destroyed'); + } + this._checkArguments(args); + const f32 = this.f32; + for (const [index, region] of this._argArrayRegions) { + const value = args[index]; + utils.flattenTo( + value instanceof Input ? value.value : value, + f32.subarray(region.offset / 4, region.offset / 4 + region.flatLength) + ); + } + for (const slot of this._argScalarSlots.values()) { + this._writeScalar(slot, args[slot.index]); + } + const stepRuns = this._stepRuns; + for (let i = 0; i < stepRuns.length; i++) { + const stepRun = stepRuns[i]; + let seed = 0; + if (stepRun.usesRandom) { + seed = stepRun.randomSeed !== null ? + (stepRun.randomSeed >>> 0) : + ((Math.random() * 0x100000000) >>> 0); + } + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + } + // the one readback: slice copies results out of wasm memory only here + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === 'step') { + const data = f32.slice(read.base, read.base + read.count); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === 'arg') { + values[i] = args[read.index]; + } else { + values[i] = read.value; + } + } + if (results.kind === 'single') return values[0]; + if (results.kind === 'array') return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) { + shaped[results.entries[i].key] = values[i]; + } + return shaped; + } + + destroy() { + if (this.destroyed) return; + this.destroyed = true; + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + // same guard as Pipeline._releasePlan: gpu.destroy() may already have + // reached this kernel, and kernel destroy is not re-entrant + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) { + shortcut.destroy(); + } + } + this._extraShortcuts = []; + this._stepRuns = null; + this._resultReads = null; + this._argArrayRegions = null; + this._argScalarSlots = null; + this.memory = null; + this.f32 = null; + this.i32 = null; + } +} + +module.exports = { + WebAssemblyPipelineExecutor, + FusionFallback, +}; \ No newline at end of file diff --git a/src/gpu.js b/src/gpu.js index c17a361c..d472f1d4 100644 --- a/src/gpu.js +++ b/src/gpu.js @@ -608,6 +608,9 @@ class GPU { Object.defineProperty(shortcut, 'executorKind', { get: () => pipeline.executorKind, }); + Object.defineProperty(shortcut, 'fallbackReason', { + get: () => pipeline.fallbackReason, + }); Object.defineProperty(shortcut, 'plan', { get: () => pipeline.plan, }); diff --git a/src/index.d.ts b/src/index.d.ts index 98174658..c39da89d 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -417,8 +417,14 @@ export interface IPipelineRunShortcut { (...args: KernelVariable[]): Promise; setConstants(constants: IConstants): this; destroy(): Promise; - /** 'generic' runs step-by-step through the normal kernel machinery on every backend */ + /** + * 'generic' runs step-by-step through the normal kernel machinery on every + * backend; 'fused-sync' runs every step over one shared wasm memory on the + * webasm backend + */ readonly executorKind: string; + /** why the fused executor declined this plan; null while fused */ + readonly fallbackReason: string | null; /** the compiled plan IR; null until the first call builds it */ readonly plan: object | null; } diff --git a/src/pipeline.js b/src/pipeline.js index ca2c9493..033794de 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -253,11 +253,25 @@ class Pipeline { this.plan = null; /** * executor identity probe for tests and later phases: 'generic' executes - * step-by-step through the normal kernel machinery on every backend; the - * webasm fused executors (phase 2) claim their own names + * step-by-step through the normal kernel machinery on every backend; + * 'fused-sync' is the webasm executor running every step over one shared + * wasm memory * @type {String} */ this.executorKind = 'generic'; + /** + * why the fused executor declined this plan; null while fused (or before + * the first call decides) + * @type {String|null} + */ + this.fallbackReason = null; + /** + * undefined: not yet attempted for this plan; false: attempted and + * declined (generic runs); otherwise the compiled fused executor + */ + this._executor = undefined; + /** test/benchmark hook: forces the generic executor when true */ + this._fusionDisabled = false; this.destroyed = false; /** * concurrent calls to one pipeline serialize on this tail, the same @@ -282,6 +296,34 @@ class Pipeline { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { this.plan = this._buildPlan(); + this._executor = undefined; + } + if (this._executor === undefined) { + this._prepareExecutor(sampled); + } + if (this._executor) { + try { + return this._executor.execute(sampled); + } catch (e) { + if (!e || !e.isFusionFallback) throw e; + this._dropExecutor(); + if (e.recompilable) { + // argument sizes/types drifted: recompile fused for the new + // signature, like the kernel's own per-size-signature rebuild + this._prepareExecutor(sampled); + if (this._executor) { + try { + return this._executor.execute(sampled); + } catch (e2) { + if (!e2 || !e2.isFusionFallback) throw e2; + this._dropExecutor(); + this._degrade(e2.message); + } + } + } else { + this._degrade(e.message); + } + } } return this._executeGeneric(this.plan, sampled); }); @@ -364,6 +406,42 @@ class Pipeline { }; } + /** + * Attempts the webasm fused executor for the current plan against this + * call's sampled arguments. Anything the webasm backend cannot take — + * including a non-webasm backend — degrades to the generic executor with + * the reason recorded, its usual degradation contract. + * @param {Array} args - sampled pipeline arguments; sizes/types bake into + * the fused layout + */ + _prepareExecutor(args) { + if (this._fusionDisabled) { + this._executor = false; + return; + } + try { + const { WebAssemblyPipelineExecutor } = require('./backend/web-assembly/pipeline-executor'); + this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); + this.executorKind = this._executor.kind; + this.fallbackReason = null; + } catch (e) { + this._degrade((e && e.message) || 'fused executor unavailable'); + } + } + + _dropExecutor() { + if (this._executor) { + this._executor.destroy(); + } + this._executor = undefined; + } + + _degrade(reason) { + this._executor = false; + this.executorKind = 'generic'; + this.fallbackReason = reason; + } + /** * The plan runs on private instances configured for pipeline use -- * `pipeline: true, immutable: true` -- so intermediates stay resident @@ -463,6 +541,12 @@ class Pipeline { } _releasePlan() { + if (this._executor) { + this._executor.destroy(); + } + this._executor = undefined; + this.executorKind = 'generic'; + this.fallbackReason = null; if (!this.plan) return; const kernels = this.plan.kernels; const gpuKernels = this.gpu && this.gpu.kernels; diff --git a/test/all.html b/test/all.html index d6ccb22e..0aebb8e8 100644 --- a/test/all.html +++ b/test/all.html @@ -309,6 +309,7 @@ + diff --git a/test/features/pipeline/correctness.js b/test/features/pipeline/correctness.js index f65bea51..bbe31f70 100644 --- a/test/features/pipeline/correctness.js +++ b/test/features/pipeline/correctness.js @@ -4,9 +4,10 @@ const { GPU } = require('../../../src'); describe('features: pipeline correctness'); // Every scenario runs against a plain-JS reference on every backend -// available here (cpu, webasm, and headlessgl where supported), through the -// generic executor -- asserted by executorKind so a later fused executor -// cannot silently take these tests over. +// available here (cpu, webasm, and headlessgl where supported). executorKind +// is asserted per mode: webasm compiles these plans to the fused executor, +// and a forced-generic webasm variant keeps the correctness-reference +// executor covered on that backend too. function assertClose(assert, actual, expected, label) { const values = Array.from(actual); @@ -19,12 +20,20 @@ function assertClose(assert, actual, expected, label) { } function eachMode(name, body) { - test(`${ name } cpu`, assert => body(assert, 'cpu')); - test(`${ name } webasm`, assert => body(assert, 'webasm')); - (GPU.isHeadlessGLSupported ? test : skip)(`${ name } headlessgl`, assert => body(assert, 'headlessgl')); + test(`${ name } cpu`, assert => body(assert, 'cpu', 'generic')); + test(`${ name } webasm`, assert => body(assert, 'webasm', 'fused-sync')); + test(`${ name } webasm (generic forced)`, assert => body(assert, 'webasm', 'generic')); + (GPU.isHeadlessGLSupported ? test : skip)(`${ name } headlessgl`, assert => body(assert, 'headlessgl', 'generic')); } -eachMode('jacobi-like ping-pong through one kernel', async (assert, mode) => { +// the test/benchmark hook: fusion is skipped entirely, the plan runs generic +function applyExecutor(shortcut, expectedKind) { + if (expectedKind === 'generic') { + shortcut.pipeline._fusionDisabled = true; + } +} + +eachMode('jacobi-like ping-pong through one kernel', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const sweep = gpu.createKernel(function (u, q) { let left = this.thread.x - 1; @@ -39,6 +48,7 @@ eachMode('jacobi-like ping-pong through one kernel', async (assert, mode) => { } return u; }, { constants: { sweeps: 6 } }); + applyExecutor(solve, kind); const u0 = [0, 1, 2, 3, 4, 5, 6, 7]; const q = [1, 0.5, 1, 0.5, 1, 0.5, 1, 0.5]; @@ -48,12 +58,12 @@ eachMode('jacobi-like ping-pong through one kernel', async (assert, mode) => { for (let s = 0; s < 6; s++) { expected = expected.map((_, x) => 0.25 * (expected[Math.max(x - 1, 0)] + expected[Math.min(x + 1, 7)]) + q[x]); } - assert.equal(solve.executorKind, 'generic', 'phase 1 runs the generic executor'); + assert.equal(solve.executorKind, kind, `runs the ${ kind } executor`); assertClose(assert, result, expected, 'jacobi'); gpu.destroy(); }); -eachMode('multi-kernel chain', async (assert, mode) => { +eachMode('multi-kernel chain', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const double = gpu.createKernel(function (a) { return a[this.thread.x] * 2; @@ -69,16 +79,17 @@ eachMode('multi-kernel chain', async (assert, mode) => { const b = addOne(a); return mix(b, a); }); + applyExecutor(chain, kind); const x = [1, 2, 3, 4, 5, 6]; const result = await chain(x); const expected = x.map(v => (v * 2 + 1) * (v * 2)); - assert.equal(chain.executorKind, 'generic'); + assert.equal(chain.executorKind, kind); assertClose(assert, result, expected, 'chain'); gpu.destroy(); }); -eachMode('multi-output object return', async (assert, mode) => { +eachMode('multi-output object return', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const double = gpu.createKernel(function (a) { return a[this.thread.x] * 2; @@ -92,16 +103,18 @@ eachMode('multi-output object return', async (assert, mode) => { negated: negate(x), }; }); + applyExecutor(both, kind); const x = [1, 2, 3, 4]; const result = await both(x); + assert.equal(both.executorKind, kind); assert.deepEqual(Object.keys(result).sort(), ['doubled', 'negated'], 'resolves to the same object shape'); assertClose(assert, result.doubled, [2, 4, 6, 8], 'doubled'); assertClose(assert, result.negated, [-1, -2, -3, -4], 'negated'); gpu.destroy(); }); -eachMode('array return resolves to an array of plain results', async (assert, mode) => { +eachMode('array return resolves to an array of plain results', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const double = gpu.createKernel(function (a) { return a[this.thread.x] * 2; @@ -110,14 +123,16 @@ eachMode('array return resolves to an array of plain results', async (assert, mo const once = double(x); return [once, double(once)]; }); + applyExecutor(pair, kind); const result = await pair([1, 2, 3, 4]); + assert.equal(pair.executorKind, kind); assert.equal(result.length, 2); assertClose(assert, result[0], [2, 4, 6, 8], 'first'); assertClose(assert, result[1], [4, 8, 12, 16], 'second'); gpu.destroy(); }); -eachMode('literal and closure-captured kernel arguments', async (assert, mode) => { +eachMode('literal and closure-captured kernel arguments', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const scale = gpu.createKernel(function (a, k) { return a[this.thread.x] * k; @@ -129,13 +144,15 @@ eachMode('literal and closure-captured kernel arguments', async (assert, mode) = const solve = gpu.createPipeline(function (x) { return offset(scale(x, 3), captured); }); + applyExecutor(solve, kind); const result = await solve([1, 2, 3, 4]); + assert.equal(solve.executorKind, kind); assertClose(assert, result, [13, 26, 39, 52], 'literal scalar and captured array'); gpu.destroy(); }); -eachMode('pipeline arg reused by several steps', async (assert, mode) => { +eachMode('pipeline arg reused by several steps', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const add = gpu.createKernel(function (a, b) { return a[this.thread.x] + b[this.thread.x]; @@ -145,13 +162,15 @@ eachMode('pipeline arg reused by several steps', async (assert, mode) => { const b = add(a, q); return add(b, q); }); + applyExecutor(solve, kind); const result = await solve([1, 2, 3, 4], [10, 10, 10, 10]); + assert.equal(solve.executorKind, kind); assertClose(assert, result, [31, 32, 33, 34], 'q consumed by three steps'); gpu.destroy(); }); -eachMode('2d output kernels', async (assert, mode) => { +eachMode('2d output kernels', async (assert, mode, kind) => { const gpu = new GPU({ mode }); const grow = gpu.createKernel(function (m) { return m[this.thread.y][this.thread.x] + 1; @@ -162,8 +181,10 @@ eachMode('2d output kernels', async (assert, mode) => { } return m; }, { constants: { passes: 3 } }); + applyExecutor(solve, kind); const result = await solve([[0, 1, 2], [10, 11, 12]]); + assert.equal(solve.executorKind, kind); assert.equal(result.length, 2, '2d shape survives readback'); assertClose(assert, result[0], [3, 4, 5], 'row 0'); assertClose(assert, result[1], [13, 14, 15], 'row 1'); diff --git a/test/features/pipeline/fused-webasm.js b/test/features/pipeline/fused-webasm.js new file mode 100644 index 00000000..12613571 --- /dev/null +++ b/test/features/pipeline/fused-webasm.js @@ -0,0 +1,402 @@ +const { assert, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); +const { utils } = require('../../../src/utils'); + +describe('features: pipeline fused webasm executor'); + +// The fused executor compiles every plan step over ONE shared wasm memory; +// each scenario here asserts executorKind === 'fused-sync' so a silent fall +// back to the generic executor fails the suite, and results are checked +// against the same pipeline forced onto the cpu backend. + +function assertClose(assert, actual, expected, label) { + const values = Array.from(actual); + assert.equal(values.length, expected.length, `${ label }: length`); + for (let i = 0; i < values.length; i++) { + const delta = Math.abs(values[i] - expected[i]); + const scale = Math.max(Math.abs(expected[i]), 1); + assert.ok(delta / scale <= 1e-5, `${ label } cell ${ i }: ${ values[i] } vs ${ expected[i] }`); + } +} + +/** + * Builds the same kernels + pipeline on webasm and on cpu, runs both with + * the same arguments, asserts the webasm one fused and answers match the + * cpu reference. + */ +async function fusedVsCpu(assert, makePipeline, argsList, compare) { + const webasm = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const fusedPipeline = makePipeline(webasm); + const referencePipeline = makePipeline(cpu); + for (let i = 0; i < argsList.length; i++) { + const fused = await fusedPipeline.apply(null, argsList[i]); + const reference = await referencePipeline.apply(null, argsList[i]); + compare(fused, reference, `call ${ i }`); + } + assert.equal(fusedPipeline.executorKind, 'fused-sync', 'webasm compiled the fused executor'); + assert.equal(fusedPipeline.fallbackReason, null, 'no fallback reason while fused'); + assert.equal(referencePipeline.executorKind, 'generic', 'cpu stays generic'); + webasm.destroy(); + cpu.destroy(); +} + +test('jacobi ping-pong: one kernel, two module instances, args re-sampled per call', async assert => { + await fusedVsCpu(assert, gpu => { + const sweep = gpu.createKernel(function (u, q) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + let right = this.thread.x + 1; + if (right > 7) right = 7; + return 0.25 * (u[left] + u[right]) + q[this.thread.x]; + }, { output: [8] }); + return gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 7 } }); + }, [ + [[0, 1, 2, 3, 4, 5, 6, 7], [1, 0.5, 1, 0.5, 1, 0.5, 1, 0.5]], + // second call: different values through the SAME compiled layout + [[7, 6, 5, 4, 3, 2, 1, 0], [0.5, 1, 0.5, 1, 0.5, 1, 0.5, 1]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +test('multi-kernel chain with double-buffer liveness (step 3 reads step 1)', async assert => { + await fusedVsCpu(assert, gpu => { + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const dbl = gpu.createKernel(function (u) { + return u[this.thread.x] * 2; + }, { output: [4] }); + const mix = gpu.createKernel(function (a, b) { + return a[this.thread.x] * 100 + b[this.thread.x]; + }, { output: [4] }); + return gpu.createPipeline(function (u) { + const a = inc(u); + const b = dbl(a); + return mix(b, a); + }); + }, [ + [[1, 2, 3, 4]], + [[5, 0, -3, 2.5]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +test('object and array returns, pipeline arg reused by several steps', async assert => { + await fusedVsCpu(assert, gpu => { + const add = gpu.createKernel(function (a, b) { + return a[this.thread.x] + b[this.thread.x]; + }, { output: [4] }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4] }); + return gpu.createPipeline(function (u, q) { + const a = add(u, q); + const b = add(a, q); + return { sum: add(b, q), doubledU: dbl(u), doubledQ: dbl(q) }; + }); + }, [ + [[1, 2, 3, 4], [10, 10, 10, 10]], + ], (fused, reference, label) => { + assertClose(assert, fused.sum, Array.from(reference.sum), `${ label } sum`); + assertClose(assert, fused.doubledU, Array.from(reference.doubledU), `${ label } doubled u`); + assertClose(assert, fused.doubledQ, Array.from(reference.doubledQ), `${ label } doubled q`); + }); +}); + +test('literal scalars, captured arrays, and constants upload once', async assert => { + const captured = [10, 20, 30, 40]; + await fusedVsCpu(assert, gpu => { + const scale = gpu.createKernel(function (a, k) { + return a[this.thread.x] * k + this.constants.bias[this.thread.x]; + }, { output: [4], constants: { bias: [1, 2, 3, 4] } }); + const offset = gpu.createKernel(function (a, o) { + return a[this.thread.x] + o[this.thread.x]; + }, { output: [4] }); + return gpu.createPipeline(function (x) { + return offset(scale(x, 3), captured); + }); + }, [ + [[1, 2, 3, 4]], + [[0, -1, 5, 0.5]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +test('2d output with a non-multiple-of-4 row width (scalar epilogue path)', async assert => { + await fusedVsCpu(assert, gpu => { + const blur = gpu.createKernel(function (m) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + return (m[this.thread.y][left] + m[this.thread.y][this.thread.x]) / 2 + 1; + }, { output: [7, 3] }); + return gpu.createPipeline(function (m) { + for (let i = 0; i < this.constants.passes; i++) { + m = blur(m); + } + return m; + }, { constants: { passes: 4 } }); + }, [ + [[ + [0, 1, 2, 3, 4, 5, 6], + [10, 11, 12, 13, 14, 15, 16], + [20, 21, 22, 23, 24, 25, 26], + ]], + ], (fused, reference, label) => { + assert.equal(fused.length, 3, `${ label }: 2d shape`); + for (let y = 0; y < 3; y++) { + assertClose(assert, fused[y], Array.from(reference[y]), `${ label } row ${ y }`); + } + }); +}); + +test('scalar pipeline args: float, boolean, and strict-integer slots', async assert => { + await fusedVsCpu(assert, gpu => { + const step = gpu.createKernel(function (a, k, flip) { + if (flip) { + return a[this.thread.x] - k; + } + return a[this.thread.x] + k; + }, { output: [4] }); + return gpu.createPipeline(function (x, k, flip) { + return step(step(x, k, flip), k, flip); + }); + }, [ + [[1, 2, 3, 4], 2.5, false], + [[1, 2, 3, 4], 2.5, true], + // boolean slot receiving a number: type drift, recompiles and stays fused + [[1, 2, 3, 4], 2.5, 1], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +test('Input pipeline argument', async assert => { + const { input } = require('../../../src'); + await fusedVsCpu(assert, gpu => { + const grow = gpu.createKernel(function (m) { + return m[this.thread.y][this.thread.x] + 1; + }, { output: [3, 2] }); + return gpu.createPipeline(function (m) { + return grow(grow(m)); + }); + }, [ + [input(new Float32Array([0, 1, 2, 10, 11, 12]), [3, 2])], + ], (fused, reference, label) => { + for (let y = 0; y < 2; y++) { + assertClose(assert, fused[y], Array.from(reference[y]), `${ label } row ${ y }`); + } + }); +}); + +test('Array(2)-returning step as a final result stays fused', async assert => { + await fusedVsCpu(assert, gpu => { + const inc = gpu.createKernel(function (a) { + return a[this.thread.x] + 1; + }, { output: [4] }); + const toVec = gpu.createKernel(function (a) { + return [a[this.thread.x], a[this.thread.x] * 2]; + }, { output: [4] }); + return gpu.createPipeline(function (x) { + return toVec(inc(x)); + }); + }, [ + [[1, 2, 3, 4]], + ], (fused, reference, label) => { + for (let i = 0; i < 4; i++) { + assertClose(assert, fused[i], Array.from(reference[i]), `${ label } vec ${ i }`); + } + }); +}); + +test('argument size change recompiles the fused plan and stays fused', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const total = gpu.createKernel(function (a, n) { + let sum = 0; + for (let i = 0; i < n; i++) { + sum += a[i]; + } + return sum + this.thread.x; + }, { output: [4], dynamicArguments: true, loopMaxIterations: 64 }); + const solve = gpu.createPipeline(function (x, n) { + return total(x, n); + }); + const first = await solve([1, 2, 3, 4], 4); + assert.equal(solve.executorKind, 'fused-sync'); + assertClose(assert, first, [10, 11, 12, 13], 'first size'); + const second = await solve([1, 2, 3, 4, 5, 6], 6); + assert.equal(solve.executorKind, 'fused-sync', 'still fused after a size change'); + assert.equal(solve.fallbackReason, null); + assertClose(assert, second, [21, 22, 23, 24], 'second size'); + const third = await solve([2, 2, 2, 2], 4); + assertClose(assert, third, [8, 9, 10, 11], 'back to the first size'); + gpu.destroy(); +}); + +test('strict-integer scalar followed by a float flows through one fused layout', async assert => { + // setupArguments maps inferred Integer to Number, so the slot is an f32 + // either way; this pins that an integer-first call does not bake a layout + // a float call cannot use + const gpu = new GPU({ mode: 'webasm' }); + const mul = gpu.createKernel(function (a, k) { + return a[this.thread.x] * k; + }, { output: [4], strictIntegers: true }); + const solve = gpu.createPipeline(function (x, k) { + return mul(mul(x, k), k); + }); + assertClose(assert, await solve([1, 2, 3, 4], 3), [9, 18, 27, 36], 'integer k'); + assert.equal(solve.executorKind, 'fused-sync'); + assertClose(assert, await solve([1, 2, 3, 4], 0.5), [0.25, 0.5, 0.75, 1], 'float k'); + assert.equal(solve.executorKind, 'fused-sync', 'still fused with the float value'); + gpu.destroy(); +}); + +test('intermediates never leave wasm memory: one flattenTo per array argument per call', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const sweep = gpu.createKernel(function (u, q) { + return u[this.thread.x] * 0.5 + q[this.thread.x]; + }, { output: [16] }); + const solve = gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 32 } }); + const u0 = new Float32Array(16).fill(1); + const q = new Float32Array(16).fill(0.25); + await solve(u0, q); + assert.equal(solve.executorKind, 'fused-sync'); + + // count uploads on a warm call: the 32 steps must not add any + const original = utils.flattenTo; + let flattens = 0; + utils.flattenTo = function () { + flattens++; + return original.apply(utils, arguments); + }; + try { + await solve(u0, q); + } finally { + utils.flattenTo = original; + } + assert.equal(flattens, 2, 'exactly one upload per pipeline array argument, none per step'); + gpu.destroy(); +}); + +test('degradation: an argument type the webasm backend cannot take falls back with a reason', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const flat = new Float32Array([5, 6, 7, 8]); + // quacks like a texture: webasm kernels degrade to cpu for it, and the + // pipeline's fused compile must decline for the same reason + const fakeTexture = { + type: 'NumberTexture', + toArray: () => Array.from(flat), + delete: () => {}, + }; + const addOne = gpu.createKernel(function (t) { + return t[this.thread.x] + 1; + }, { output: [4] }); + const solve = gpu.createPipeline(function (t) { + return addOne(addOne(t)); + }); + const result = await solve(fakeTexture); + assert.equal(solve.executorKind, 'generic', 'fell back to the generic executor'); + assert.ok(/not supported on the webasm backend/.test(solve.fallbackReason), `reason names the cause: ${ solve.fallbackReason }`); + assertClose(assert, result, [7, 8, 9, 10], 'generic executor still answers correctly'); + gpu.destroy(); +}); + +test('degradation: Array(2) intermediate names its reason', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const toVec = gpu.createKernel(function (a) { + return [a[this.thread.x], a[this.thread.x] * 2]; + }, { output: [4] }); + const useVec = gpu.createKernel(function (v) { + return v[this.thread.x][0] + v[this.thread.x][1]; + }, { output: [4] }); + const solve = gpu.createPipeline(function (x) { + return useVec(toVec(x)); + }); + // the webasm KERNELS cannot take the vec intermediate either (no self-typed + // values on this backend), so the call itself fails downstream; the + // pipeline-level contract under test is the named fused decline + await solve([1, 2, 3, 4]).then( + () => assert.ok(true, 'generic executor absorbed the plan'), + () => assert.ok(true, 'plan is not runnable on this backend at all') + ); + assert.equal(solve.executorKind, 'generic'); + assert.ok(/cannot feed another step/.test(solve.fallbackReason), `reason: ${ solve.fallbackReason }`); + gpu.destroy(); +}); + +test('setConstants re-traces and the new plan fuses again', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const inc = gpu.createKernel(function (a) { + return a[this.thread.x] + 1; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + for (let i = 0; i < this.constants.n; i++) { + x = inc(x); + } + return x; + }, { constants: { n: 2 } }); + assertClose(assert, await solve([0, 0, 0]), [2, 2, 2], 'n=2'); + assert.equal(solve.executorKind, 'fused-sync'); + solve.setConstants({ n: 5 }); + assertClose(assert, await solve([0, 0, 0]), [5, 5, 5], 'n=5 after re-trace'); + assert.equal(solve.executorKind, 'fused-sync', 'the re-traced plan fused too'); + gpu.destroy(); +}); + +test('concurrent fused calls serialize and answer from their own arguments', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(dbl(x)); + }); + const buf = [1, 2, 3]; + const firstCall = solve(buf); + buf[0] = 100; // sampled at call time; must not leak into the first call + const secondCall = solve(buf); + const [first, second] = await Promise.all([firstCall, secondCall]); + assertClose(assert, first, [4, 8, 12], 'first call'); + assertClose(assert, second, [400, 8, 12], 'second call'); + gpu.destroy(); +}); + +test('destroy releases every fused instance, including extra type signatures', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const before = gpu.kernels.length; + const shift = gpu.createKernel(function (a, s) { + return a[this.thread.x] + s; + }, { output: [3], strictIntegers: true }); + // integer and float scalar signatures force a second program instance for + // the same kernel + const solve = gpu.createPipeline(function (x) { + return shift(shift(x, 1), 1.5); + }); + assertClose(assert, await solve([1, 2, 3]), [3.5, 4.5, 5.5], 'two signatures'); + assert.equal(solve.executorKind, 'fused-sync'); + assert.ok(gpu.kernels.length > before + 1, 'fused compile registered private instances'); + await solve.destroy(); + assert.equal(gpu.kernels.length, before + 1, 'only the user kernel remains'); + await assert.rejects(solve([1, 2, 3]), /destroyed/, 'calls after destroy reject'); + gpu.destroy(); +}); + +test('user kernels stay independently usable while their pipeline is fused', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(dbl(x)); + }); + assertClose(assert, await solve([1, 2, 3]), [4, 8, 12], 'pipeline'); + assert.equal(solve.executorKind, 'fused-sync'); + assertClose(assert, dbl([5, 6, 7]), [10, 12, 14], 'direct call unaffected'); + assertClose(assert, await solve([2, 2, 2]), [8, 8, 8], 'pipeline again after direct use'); + gpu.destroy(); +}); From 00b22c0bb65ed2d8e0946f3e26f1581f539ebbde Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 13:29:15 +0800 Subject: [PATCH 03/16] feat: threaded fused pipeline executor with memory-resident Atomics barriers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pool workers now execute the WHOLE fused plan when threads exist and the plan crosses the kernel's 4096-cell threading floor: each worker owns a contiguous cell-range slice of every step and advances step-to-step on a generation-counter barrier living in the shared wasm memory, so a pipeline call costs exactly one pool dispatch however many steps the plan unrolls to. The main thread Atomics.waitAsync-or-polls only the final generation (pinning the event loop itself, since waitAsync does not), and executorKind reports 'fused-threaded'. Failure containment: a dead worker rejects the run through the pool's die/retire machinery and an abort word releases the survivors' barriers; a barrier that can never fill without a death is bounded by a progress-based sanity timeout; pipeline.destroy() mid-run aborts the walk and rejects the in-flight call. Any threaded failure drops the executor so the next call compiles a fresh one. Benchmark (jacobi 5-point, 1024x1024, 512 passes, checksums bit-identical): fused-threaded 356ms vs fused-sync 1457ms vs generic 1789ms — 4.1x / 5.0x. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 255 +++++++++-- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 255 +++++++++-- dist/gpu-browser.min.js | 4 +- src/backend/web-assembly/pipeline-executor.js | 276 +++++++++++- src/backend/web-assembly/worker-pool.js | 142 ++++++- src/index.d.ts | 3 +- src/pipeline.js | 35 +- test/all.html | 1 + test/features/pipeline/threaded-webasm.js | 395 ++++++++++++++++++ 10 files changed, 1292 insertions(+), 78 deletions(-) create mode 100644 test/features/pipeline/threaded-webasm.js diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index fb74f584..9d2bb2ea 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -13135,10 +13135,10 @@ const context = await WebGPUContext.acquire(); this.context = context; const device = this._device = context.device; - const module$5 = device.createShaderModule({ + const module$6 = device.createShaderModule({ code: this.compiledSource }); - const errors = (await module$5.getCompilationInfo()).messages.filter(message => message.type === "error"); + const errors = (await module$6.getCompilationInfo()).messages.filter(message => message.type === "error"); if (errors.length > 0) throw new Error("Error compiling WGSL compute shader:\n" + errors.map(message => ` ${message.lineNum}:${message.linePos} ${message.message}`).join("\n") + `\n--- generated WGSL ---\n${this.compiledSource}`); const {arrayArgs: arrayArgs, bufferConstants: bufferConstants, byteLength: byteLength} = this.paramsLayout; const layoutEntries = [ { @@ -13179,7 +13179,7 @@ bindGroupLayouts: [ this.bindGroupLayout ] }), compute: { - module: module$5, + module: module$6, entryPoint: "main" } }); @@ -14127,12 +14127,12 @@ }; return this; } - addFuncImport(name, params, results, module$3 = "env") { + addFuncImport(name, params, results, module$4 = "env") { if (name in this.funcImportIndexByName || name in this.functionIndexByName) throw new Error(`WasmModuleBuilder: duplicate function name "${name}"`); const index = this.funcImports.length; this.funcImports.push({ name: name, - module: module$3, + module: module$4, typeIndex: this._typeIndex(params, results) }); this.funcImportIndexByName[name] = index; @@ -14205,8 +14205,8 @@ uleb(initial, payload); if (hasMax) uleb(maximum, payload); } - for (const {name: name, module: module$4, typeIndex: typeIndex} of this.funcImports) { - utf8(module$4, payload); + for (const {name: name, module: module$5, typeIndex: typeIndex} of this.funcImports) { + utf8(module$5, payload); utf8(name, payload); payload.push(0); uleb(typeIndex, payload); @@ -14476,9 +14476,9 @@ } emitFunction(assembler) { this.assembler = assembler; - const {module: module$2} = assembler; + const {module: module$3} = assembler; let em; - if (this.isRootKernel) em = module$2.addFunction("kernel", { + if (this.isRootKernel) em = module$3.addFunction("kernel", { params: [], results: [] }); else { @@ -14499,7 +14499,7 @@ default: throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`); } - em = module$2.addFunction(this.mangleFunctionName(this.name), { + em = module$3.addFunction(this.mangleFunctionName(this.name), { params: params, results: results }); @@ -18130,7 +18130,7 @@ } return 4; } - const WORKER_SOURCE = `\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n`; + const WORKER_SOURCE = `\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n`; var WebAssemblyWorkerPool = class { constructor(size) { this.size = size || defaultConcurrency(); @@ -18234,7 +18234,17 @@ }); worker.state.settingUp.set(entry.id, wait); this._updateRef(worker); - worker.handle.postMessage({ + worker.handle.postMessage(entry.pipeline ? { + type: "pipelineSetup", + id: entry.id, + memory: entry.memory, + modules: entry.modules, + moduleMathImports: entry.moduleMathImports, + steps: entry.steps, + countIndex: entry.countIndex, + genIndex: entry.genIndex, + abortIndex: entry.abortIndex + } : { type: "setup", id: entry.id, module: entry.module, @@ -18277,6 +18287,40 @@ }); return Promise.all(runs).then(() => void 0); } + dispatchPipeline(entry, run) { + if (this.destroyed) return Promise.reject(new Error("WebAssembly worker pool has been destroyed")); + this.dispatchCount++; + this.lastDispatch = { + workerCount: entry.workerCount, + ranges: entry.workerRanges.map(ranges => ranges.slice()) + }; + const runs = []; + for (let index = 0; index < entry.workerCount; index++) { + const worker = this._worker(index); + runs.push(this._ensureSetup(worker, entry).then(() => new Promise((resolve, reject) => { + if (worker.dead) { + reject(new Error("WebAssembly worker died before the task could run")); + return; + } + const taskId = ++this._taskId; + worker.state.pending.set(taskId, { + resolve: resolve, + reject: reject + }); + this._updateRef(worker); + worker.handle.postMessage({ + type: "pipelineRun", + id: entry.id, + taskId: taskId, + ranges: entry.workerRanges[index], + seeds: run.seeds, + baseGen: run.baseGen, + workerCount: entry.workerCount + }); + }))); + } + return Promise.all(runs).then(() => void 0); + } release(entryId) { if (this.destroyed) return; for (const worker of this.workers) { @@ -18822,8 +18866,8 @@ } }; for (const name of this.usedMathImports) imports.env["math_" + name] = Math[name]; - const module$1 = new WebAssembly.Module(bytes); - const instance = new WebAssembly.Instance(module$1, imports); + const module$2 = new WebAssembly.Module(bytes); + const instance = new WebAssembly.Instance(module$2, imports); entry = { id: nextEntryId++, sizeSignature: entryKey, @@ -18831,7 +18875,7 @@ layout: layout, cells: cells, bytes: bytes, - module: module$1, + module: module$2, memory: memory, mathImports: Array.from(this.usedMathImports).sort(), sizeX: tx, @@ -19067,7 +19111,10 @@ const {utils: utils} = require_utils(); const {Input: Input} = require_input(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); + const {WebAssemblyWorkerPool: WebAssemblyWorkerPool} = require_worker_pool(); const SUPPORTED_VALUE_TYPES = [ "Array", "Input", "Number", "Float", "Integer", "Boolean" ]; + const THREAD_MIN_CELLS = 4096; + let nextPipelineEntryId = 1; var FusionFallback = class extends Error { constructor(reason, recompilable) { super(reason); @@ -19109,10 +19156,15 @@ this.gpu = pipeline.gpu; this.plan = plan; this.kind = "fused-sync"; + this.threaded = false; this.destroyed = false; this.memory = null; this.f32 = null; this.i32 = null; + this.pool = null; + this.sanityTimeoutMs = 1e4; + this._entry = null; + this._abortError = null; this._stepRuns = null; this._argArrayRegions = null; this._argScalarSlots = null; @@ -19168,6 +19220,25 @@ offset = align16(offset + bytes); return at; }; + let threadWorkerCount = 0; + let controlOffset = -1; + if (!this.pipeline._threadsDisabled && WebAssemblyKernel.isThreadsSupported) { + let maxCells = 0; + for (let i = 0; i < plan.steps.length; i++) { + const output = plan.steps[i].output; + let cells = 1; + for (let d = 0; d < output.length; d++) cells *= output[d]; + if (cells > maxCells) maxCells = cells; + } + const pool = new WebAssemblyWorkerPool; + threadWorkerCount = Math.min(pool.size, Math.ceil(maxCells / THREAD_MIN_CELLS)); + if (threadWorkerCount > 1) { + this.threaded = true; + this.kind = "fused-threaded"; + this.pool = pool; + controlOffset = alloc(12); + } else pool.destroy(); + } const argArrayRegions = new Map; const argScalarSlots = new Map; const literalArrayRegions = new Map; @@ -19296,6 +19367,8 @@ const totalBytes = offset; const moduleCache = new Map; const stepRuns = new Array(plan.steps.length); + const threadModules = []; + const threadModuleImports = []; for (let i = 0; i < plan.steps.length; i++) { const program = stepPrograms[i]; const kernel = program.kernel; @@ -19317,9 +19390,13 @@ totalBytes: totalBytes }; const cells = bufferRegions[plan.steps[i].outputBuffer].cells; - const assembled = kernel._assembleModule(layout, cells, false); + const assembled = kernel._assembleModule(layout, cells, this.threaded); if (this.memory === null) { - this.memory = new WebAssembly.Memory({ + this.memory = this.threaded ? new WebAssembly.Memory({ + initial: assembled.initial, + maximum: assembled.maximum, + shared: true + }) : new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum }); @@ -19332,22 +19409,63 @@ } }; for (const name of kernel.usedMathImports) imports.env["math_" + name] = Math[name]; - const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + const module$1 = new WebAssembly.Module(assembled.bytes); + const instance = new WebAssembly.Instance(module$1, imports); compiled = { run: instance.exports.run, - runSimd: instance.exports.run_simd || null + runSimd: instance.exports.run_simd || null, + moduleIndex: threadModules.length }; + threadModules.push(module$1); + threadModuleImports.push(Array.from(kernel.usedMathImports).sort()); moduleCache.set(moduleKey, compiled); } stepRuns[i] = { run: compiled.run, runSimd: compiled.runSimd, + moduleIndex: compiled.moduleIndex, cells: bufferRegions[plan.steps[i].outputBuffer].cells, sizeX: kernel.threadDim[0], usesRandom: kernel.usesRandom, randomSeed: kernel.randomSeed }; } + if (this.threaded) { + const workerRanges = []; + for (let w = 0; w < threadWorkerCount; w++) { + const ranges = new Array(plan.steps.length * 2); + for (let i = 0; i < plan.steps.length; i++) { + const cells = stepRuns[i].cells; + let chunk = Math.ceil(cells / threadWorkerCount) & -4; + if (chunk < 4) chunk = 4; + const start = w * chunk; + if (start >= cells) { + ranges[i * 2] = 0; + ranges[i * 2 + 1] = 0; + } else { + ranges[i * 2] = start; + ranges[i * 2 + 1] = w === threadWorkerCount - 1 ? cells : Math.min(start + chunk, cells); + } + } + workerRanges.push(ranges); + } + this._entry = { + id: "pipeline:" + nextPipelineEntryId++, + pipeline: true, + memory: this.memory, + modules: threadModules, + moduleMathImports: threadModuleImports, + steps: stepRuns.map(stepRun => ({ + module: stepRun.moduleIndex, + sizeX: stepRun.sizeX + })), + countIndex: controlOffset / 4, + genIndex: controlOffset / 4 + 1, + abortIndex: controlOffset / 4 + 2, + workerCount: threadWorkerCount, + workerRanges: workerRanges + }; + } for (let i = 0; i < uploadArrays.length; i++) { const upload = uploadArrays[i]; utils.flattenTo(upload.value instanceof Input ? upload.value.value : upload.value, this.f32.subarray(upload.offset / 4, upload.offset / 4 + upload.flatLength)); @@ -19425,6 +19543,7 @@ } execute(args) { if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + if (this._abortError) throw this._abortError; this._checkArguments(args); const f32 = this.f32; for (const [index, region] of this._argArrayRegions) { @@ -19432,13 +19551,84 @@ utils.flattenTo(value instanceof Input ? value.value : value, f32.subarray(region.offset / 4, region.offset / 4 + region.flatLength)); } for (const slot of this._argScalarSlots.values()) this._writeScalar(slot, args[slot.index]); + if (this.threaded) return this._executeThreaded(args); const stepRuns = this._stepRuns; for (let i = 0; i < stepRuns.length; i++) { const stepRun = stepRuns[i]; - let seed = 0; - if (stepRun.usesRandom) seed = stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; - WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, this._drawSeed(stepRun)); + } + return this._readResults(args); + } + _drawSeed(stepRun) { + if (!stepRun.usesRandom) return 0; + return (stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0) | 0; + } + _executeThreaded(args) { + const entry = this._entry; + const i32 = this.i32; + Atomics.store(i32, entry.genIndex, 0); + Atomics.store(i32, entry.countIndex, 0); + const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); + const finalGen = this._stepRuns.length; + this.pool.dispatchPipeline(entry, { + baseGen: 0, + seeds: seeds + }).then(null, error => this._abort(error)); + return this._waitForGeneration(finalGen).then(() => this._readResults(args)); + } + _waitForGeneration(target) { + const i32 = this.i32; + const genIndex = this._entry.genIndex; + const waitAsync = typeof Atomics.waitAsync === "function" ? Atomics.waitAsync : null; + return new Promise((resolve, reject) => { + const keepAlive = typeof setInterval === "function" ? setInterval(() => {}, 200) : null; + const settle = (fn, value) => { + if (keepAlive !== null) clearInterval(keepAlive); + fn(value); + }; + let lastSeen = Atomics.load(i32, genIndex); + let lastProgress = Date.now(); + const check = () => { + if (this._abortError) { + settle(reject, this._abortError); + return; + } + const gen = Atomics.load(i32, genIndex); + if (gen >= target) { + settle(resolve); + return; + } + if (gen !== lastSeen) { + lastSeen = gen; + lastProgress = Date.now(); + } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { + const error = new Error(`pipeline threaded barrier stalled at generation ${gen} of ${target} for ${this.sanityTimeoutMs}ms`); + this._abort(error); + settle(reject, error); + return; + } + if (waitAsync) { + const slice = Math.max(1, Math.min(200, this.sanityTimeoutMs)); + const wait = waitAsync(i32, genIndex, gen, slice); + if (wait.async) wait.value.then(check); else Promise.resolve().then(check); + } else setTimeout(check, 1); + }; + check(); + }); + } + _abort(error) { + if (this._abortError) return; + this._abortError = error || new Error("pipeline threaded run aborted"); + if (this.i32 && this._entry) { + Atomics.store(this.i32, this._entry.abortIndex, 1); + Atomics.notify(this.i32, this._entry.genIndex); } + } + abortRuns(error) { + if (this.threaded) this._abort(error); + } + _readResults(args) { + const f32 = this.f32; const results = this.plan.results; const values = new Array(this._resultReads.length); for (let i = 0; i < this._resultReads.length; i++) { @@ -19457,12 +19647,18 @@ destroy() { if (this.destroyed) return; this.destroyed = true; + if (this.pool) { + this._abort(new Error("pipeline fused executor has been destroyed")); + this.pool.destroy(); + this.pool = null; + } const gpuKernels = this.gpu && this.gpu.kernels; for (let i = 0; i < this._extraShortcuts.length; i++) { const shortcut = this._extraShortcuts[i]; if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); } this._extraShortcuts = []; + this._entry = null; this._stepRuns = null; this._resultReads = null; this._argArrayRegions = null; @@ -19641,6 +19837,7 @@ this.fallbackReason = null; this._executor = void 0; this._fusionDisabled = false; + this._threadsDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -19656,14 +19853,14 @@ } if (this._executor === void 0) this._prepareExecutor(sampled); if (this._executor) try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); if (e.recompilable) { this._prepareExecutor(sampled); if (this._executor) try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -19676,6 +19873,13 @@ this._tail = promise.then(noop, noop); return promise; } + _guardAsync(result) { + if (result && typeof result.then === "function") return result.then(null, error => { + this._dropExecutor(); + throw error; + }); + return result; + } setConstants(constants) { this.constants = Object.assign({}, constants || {}); const release = () => { @@ -19690,6 +19894,7 @@ const index = this.gpu.pipelines.indexOf(this); if (index !== -1) this.gpu.pipelines.splice(index, 1); } + if (this._executor && typeof this._executor.abortRuns === "function") this._executor.abortRuns(new Error(MSG_DESTROYED)); const release = () => { this._releasePlan(); }; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 61d2a931..cd0634f9 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),L=(e,t,r)=>{B.assignArgumentType(e,t,r)},k=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:k,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:L,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=k();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=k();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=L(),{GLTextureUnsigned:V}=k(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:L,immutable:k,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:L}=me(),{WebGLKernelValueDynamicUnsignedArray:k}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=Le();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=Le(),{WebGL2KernelValueDynamicHTMLImageArray:u}=ke(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:L}=He(),{WebGL2KernelValueArray4:k}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":L,"Array(4)":k,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),o=["Array","Input","Number","Float","Integer","Boolean"];var u=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,c)).join(",");let d=n.get(p);if(!d){let e;if(i[u.kernel]){const t=this.pipeline._cloneKernel(l.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[u.kernel]=!0,e=l.clone.kernel;this._prepareKernel(e,h),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}a[s]=d,o[s]=h}for(let e=0;e{const t=l;return l=(e=>16*Math.ceil(e/16))(l+e),t},c=new Map,p=new Map,d=new Map,f=[],m=[],g=[],y=new Array(t.steps.length);for(let e=0;e${i}`;let l=T.get(u);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:v},o=b[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,o,!1);null===this.memory&&(this.memory=new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Instance(new WebAssembly.Module(h.bytes),c);l={run:p.exports.run,runSimd:p.exports.run_simd||null},T.set(u,l)}S[e]={run:l.run,runSimd:l.runSimd,cells:b[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=b[t.steps[e].outputBuffer],s=a[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=S,this._argArrayRegions=c,this._argScalarSlots=p,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0),a.dispatchSpans(t.run,t.runSimd,t.cells,t.sizeX,0|r)}const i=this.plan.results,o=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:L}=tt(),{WebGPUKernel:k}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:L,WebGPUKernel:k,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,r)=>{B.assignArgumentType(e,t,r)},L=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),C=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:_,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=I.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:E},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),I.set(o,l)}_[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:_.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=_,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32;Atomics.store(r,t.genIndex,0),Atomics.store(r,t.countIndex,0);const n=this._stepRuns.map(e=>this._drawSeed(e)),s=this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:0,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(s).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)};let u=Atomics.load(t,r),l=Date.now();const h=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)o(s);else{if(a!==u)u=a,l=Date.now();else if(Date.now()-l>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(h):Promise.resolve().then(h)}else setTimeout(h,1)}};h()})}_abort(e){this._abortError||(this._abortError=e||new Error("pipeline threaded run aborted"),this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)))}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index b651cbd2..afebe81d 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -17332,10 +17332,10 @@ const context = await WebGPUContext.acquire(); this.context = context; const device = this._device = context.device; - const module$5 = device.createShaderModule({ + const module$6 = device.createShaderModule({ code: this.compiledSource }); - const errors = (await module$5.getCompilationInfo()).messages.filter(message => message.type === "error"); + const errors = (await module$6.getCompilationInfo()).messages.filter(message => message.type === "error"); if (errors.length > 0) throw new Error("Error compiling WGSL compute shader:\n" + errors.map(message => ` ${message.lineNum}:${message.linePos} ${message.message}`).join("\n") + `\n--- generated WGSL ---\n${this.compiledSource}`); const {arrayArgs: arrayArgs, bufferConstants: bufferConstants, byteLength: byteLength} = this.paramsLayout; const layoutEntries = [ { @@ -17376,7 +17376,7 @@ bindGroupLayouts: [ this.bindGroupLayout ] }), compute: { - module: module$5, + module: module$6, entryPoint: "main" } }); @@ -18324,12 +18324,12 @@ }; return this; } - addFuncImport(name, params, results, module$3 = "env") { + addFuncImport(name, params, results, module$4 = "env") { if (name in this.funcImportIndexByName || name in this.functionIndexByName) throw new Error(`WasmModuleBuilder: duplicate function name "${name}"`); const index = this.funcImports.length; this.funcImports.push({ name: name, - module: module$3, + module: module$4, typeIndex: this._typeIndex(params, results) }); this.funcImportIndexByName[name] = index; @@ -18402,8 +18402,8 @@ uleb(initial, payload); if (hasMax) uleb(maximum, payload); } - for (const {name: name, module: module$4, typeIndex: typeIndex} of this.funcImports) { - utf8(module$4, payload); + for (const {name: name, module: module$5, typeIndex: typeIndex} of this.funcImports) { + utf8(module$5, payload); utf8(name, payload); payload.push(0); uleb(typeIndex, payload); @@ -18673,9 +18673,9 @@ } emitFunction(assembler) { this.assembler = assembler; - const {module: module$2} = assembler; + const {module: module$3} = assembler; let em; - if (this.isRootKernel) em = module$2.addFunction("kernel", { + if (this.isRootKernel) em = module$3.addFunction("kernel", { params: [], results: [] }); else { @@ -18696,7 +18696,7 @@ default: throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`); } - em = module$2.addFunction(this.mangleFunctionName(this.name), { + em = module$3.addFunction(this.mangleFunctionName(this.name), { params: params, results: results }); @@ -22327,7 +22327,7 @@ } return 4; } - const WORKER_SOURCE = `\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n`; + const WORKER_SOURCE = `\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n`; var WebAssemblyWorkerPool = class { constructor(size) { this.size = size || defaultConcurrency(); @@ -22431,7 +22431,17 @@ }); worker.state.settingUp.set(entry.id, wait); this._updateRef(worker); - worker.handle.postMessage({ + worker.handle.postMessage(entry.pipeline ? { + type: "pipelineSetup", + id: entry.id, + memory: entry.memory, + modules: entry.modules, + moduleMathImports: entry.moduleMathImports, + steps: entry.steps, + countIndex: entry.countIndex, + genIndex: entry.genIndex, + abortIndex: entry.abortIndex + } : { type: "setup", id: entry.id, module: entry.module, @@ -22474,6 +22484,40 @@ }); return Promise.all(runs).then(() => void 0); } + dispatchPipeline(entry, run) { + if (this.destroyed) return Promise.reject(new Error("WebAssembly worker pool has been destroyed")); + this.dispatchCount++; + this.lastDispatch = { + workerCount: entry.workerCount, + ranges: entry.workerRanges.map(ranges => ranges.slice()) + }; + const runs = []; + for (let index = 0; index < entry.workerCount; index++) { + const worker = this._worker(index); + runs.push(this._ensureSetup(worker, entry).then(() => new Promise((resolve, reject) => { + if (worker.dead) { + reject(new Error("WebAssembly worker died before the task could run")); + return; + } + const taskId = ++this._taskId; + worker.state.pending.set(taskId, { + resolve: resolve, + reject: reject + }); + this._updateRef(worker); + worker.handle.postMessage({ + type: "pipelineRun", + id: entry.id, + taskId: taskId, + ranges: entry.workerRanges[index], + seeds: run.seeds, + baseGen: run.baseGen, + workerCount: entry.workerCount + }); + }))); + } + return Promise.all(runs).then(() => void 0); + } release(entryId) { if (this.destroyed) return; for (const worker of this.workers) { @@ -23019,8 +23063,8 @@ } }; for (const name of this.usedMathImports) imports.env["math_" + name] = Math[name]; - const module$1 = new WebAssembly.Module(bytes); - const instance = new WebAssembly.Instance(module$1, imports); + const module$2 = new WebAssembly.Module(bytes); + const instance = new WebAssembly.Instance(module$2, imports); entry = { id: nextEntryId++, sizeSignature: entryKey, @@ -23028,7 +23072,7 @@ layout: layout, cells: cells, bytes: bytes, - module: module$1, + module: module$2, memory: memory, mathImports: Array.from(this.usedMathImports).sort(), sizeX: tx, @@ -23264,7 +23308,10 @@ const {utils: utils} = require_utils(); const {Input: Input} = require_input(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); + const {WebAssemblyWorkerPool: WebAssemblyWorkerPool} = require_worker_pool(); const SUPPORTED_VALUE_TYPES = [ "Array", "Input", "Number", "Float", "Integer", "Boolean" ]; + const THREAD_MIN_CELLS = 4096; + let nextPipelineEntryId = 1; var FusionFallback = class extends Error { constructor(reason, recompilable) { super(reason); @@ -23306,10 +23353,15 @@ this.gpu = pipeline.gpu; this.plan = plan; this.kind = "fused-sync"; + this.threaded = false; this.destroyed = false; this.memory = null; this.f32 = null; this.i32 = null; + this.pool = null; + this.sanityTimeoutMs = 1e4; + this._entry = null; + this._abortError = null; this._stepRuns = null; this._argArrayRegions = null; this._argScalarSlots = null; @@ -23365,6 +23417,25 @@ offset = align16(offset + bytes); return at; }; + let threadWorkerCount = 0; + let controlOffset = -1; + if (!this.pipeline._threadsDisabled && WebAssemblyKernel.isThreadsSupported) { + let maxCells = 0; + for (let i = 0; i < plan.steps.length; i++) { + const output = plan.steps[i].output; + let cells = 1; + for (let d = 0; d < output.length; d++) cells *= output[d]; + if (cells > maxCells) maxCells = cells; + } + const pool = new WebAssemblyWorkerPool; + threadWorkerCount = Math.min(pool.size, Math.ceil(maxCells / THREAD_MIN_CELLS)); + if (threadWorkerCount > 1) { + this.threaded = true; + this.kind = "fused-threaded"; + this.pool = pool; + controlOffset = alloc(12); + } else pool.destroy(); + } const argArrayRegions = new Map; const argScalarSlots = new Map; const literalArrayRegions = new Map; @@ -23493,6 +23564,8 @@ const totalBytes = offset; const moduleCache = new Map; const stepRuns = new Array(plan.steps.length); + const threadModules = []; + const threadModuleImports = []; for (let i = 0; i < plan.steps.length; i++) { const program = stepPrograms[i]; const kernel = program.kernel; @@ -23514,9 +23587,13 @@ totalBytes: totalBytes }; const cells = bufferRegions[plan.steps[i].outputBuffer].cells; - const assembled = kernel._assembleModule(layout, cells, false); + const assembled = kernel._assembleModule(layout, cells, this.threaded); if (this.memory === null) { - this.memory = new WebAssembly.Memory({ + this.memory = this.threaded ? new WebAssembly.Memory({ + initial: assembled.initial, + maximum: assembled.maximum, + shared: true + }) : new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum }); @@ -23529,22 +23606,63 @@ } }; for (const name of kernel.usedMathImports) imports.env["math_" + name] = Math[name]; - const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + const module$1 = new WebAssembly.Module(assembled.bytes); + const instance = new WebAssembly.Instance(module$1, imports); compiled = { run: instance.exports.run, - runSimd: instance.exports.run_simd || null + runSimd: instance.exports.run_simd || null, + moduleIndex: threadModules.length }; + threadModules.push(module$1); + threadModuleImports.push(Array.from(kernel.usedMathImports).sort()); moduleCache.set(moduleKey, compiled); } stepRuns[i] = { run: compiled.run, runSimd: compiled.runSimd, + moduleIndex: compiled.moduleIndex, cells: bufferRegions[plan.steps[i].outputBuffer].cells, sizeX: kernel.threadDim[0], usesRandom: kernel.usesRandom, randomSeed: kernel.randomSeed }; } + if (this.threaded) { + const workerRanges = []; + for (let w = 0; w < threadWorkerCount; w++) { + const ranges = new Array(plan.steps.length * 2); + for (let i = 0; i < plan.steps.length; i++) { + const cells = stepRuns[i].cells; + let chunk = Math.ceil(cells / threadWorkerCount) & -4; + if (chunk < 4) chunk = 4; + const start = w * chunk; + if (start >= cells) { + ranges[i * 2] = 0; + ranges[i * 2 + 1] = 0; + } else { + ranges[i * 2] = start; + ranges[i * 2 + 1] = w === threadWorkerCount - 1 ? cells : Math.min(start + chunk, cells); + } + } + workerRanges.push(ranges); + } + this._entry = { + id: "pipeline:" + nextPipelineEntryId++, + pipeline: true, + memory: this.memory, + modules: threadModules, + moduleMathImports: threadModuleImports, + steps: stepRuns.map(stepRun => ({ + module: stepRun.moduleIndex, + sizeX: stepRun.sizeX + })), + countIndex: controlOffset / 4, + genIndex: controlOffset / 4 + 1, + abortIndex: controlOffset / 4 + 2, + workerCount: threadWorkerCount, + workerRanges: workerRanges + }; + } for (let i = 0; i < uploadArrays.length; i++) { const upload = uploadArrays[i]; utils.flattenTo(upload.value instanceof Input ? upload.value.value : upload.value, this.f32.subarray(upload.offset / 4, upload.offset / 4 + upload.flatLength)); @@ -23622,6 +23740,7 @@ } execute(args) { if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + if (this._abortError) throw this._abortError; this._checkArguments(args); const f32 = this.f32; for (const [index, region] of this._argArrayRegions) { @@ -23629,13 +23748,84 @@ utils.flattenTo(value instanceof Input ? value.value : value, f32.subarray(region.offset / 4, region.offset / 4 + region.flatLength)); } for (const slot of this._argScalarSlots.values()) this._writeScalar(slot, args[slot.index]); + if (this.threaded) return this._executeThreaded(args); const stepRuns = this._stepRuns; for (let i = 0; i < stepRuns.length; i++) { const stepRun = stepRuns[i]; - let seed = 0; - if (stepRun.usesRandom) seed = stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0; - WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, this._drawSeed(stepRun)); + } + return this._readResults(args); + } + _drawSeed(stepRun) { + if (!stepRun.usesRandom) return 0; + return (stepRun.randomSeed !== null ? stepRun.randomSeed >>> 0 : Math.random() * 4294967296 >>> 0) | 0; + } + _executeThreaded(args) { + const entry = this._entry; + const i32 = this.i32; + Atomics.store(i32, entry.genIndex, 0); + Atomics.store(i32, entry.countIndex, 0); + const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); + const finalGen = this._stepRuns.length; + this.pool.dispatchPipeline(entry, { + baseGen: 0, + seeds: seeds + }).then(null, error => this._abort(error)); + return this._waitForGeneration(finalGen).then(() => this._readResults(args)); + } + _waitForGeneration(target) { + const i32 = this.i32; + const genIndex = this._entry.genIndex; + const waitAsync = typeof Atomics.waitAsync === "function" ? Atomics.waitAsync : null; + return new Promise((resolve, reject) => { + const keepAlive = typeof setInterval === "function" ? setInterval(() => {}, 200) : null; + const settle = (fn, value) => { + if (keepAlive !== null) clearInterval(keepAlive); + fn(value); + }; + let lastSeen = Atomics.load(i32, genIndex); + let lastProgress = Date.now(); + const check = () => { + if (this._abortError) { + settle(reject, this._abortError); + return; + } + const gen = Atomics.load(i32, genIndex); + if (gen >= target) { + settle(resolve); + return; + } + if (gen !== lastSeen) { + lastSeen = gen; + lastProgress = Date.now(); + } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { + const error = new Error(`pipeline threaded barrier stalled at generation ${gen} of ${target} for ${this.sanityTimeoutMs}ms`); + this._abort(error); + settle(reject, error); + return; + } + if (waitAsync) { + const slice = Math.max(1, Math.min(200, this.sanityTimeoutMs)); + const wait = waitAsync(i32, genIndex, gen, slice); + if (wait.async) wait.value.then(check); else Promise.resolve().then(check); + } else setTimeout(check, 1); + }; + check(); + }); + } + _abort(error) { + if (this._abortError) return; + this._abortError = error || new Error("pipeline threaded run aborted"); + if (this.i32 && this._entry) { + Atomics.store(this.i32, this._entry.abortIndex, 1); + Atomics.notify(this.i32, this._entry.genIndex); } + } + abortRuns(error) { + if (this.threaded) this._abort(error); + } + _readResults(args) { + const f32 = this.f32; const results = this.plan.results; const values = new Array(this._resultReads.length); for (let i = 0; i < this._resultReads.length; i++) { @@ -23654,12 +23844,18 @@ destroy() { if (this.destroyed) return; this.destroyed = true; + if (this.pool) { + this._abort(new Error("pipeline fused executor has been destroyed")); + this.pool.destroy(); + this.pool = null; + } const gpuKernels = this.gpu && this.gpu.kernels; for (let i = 0; i < this._extraShortcuts.length; i++) { const shortcut = this._extraShortcuts[i]; if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); } this._extraShortcuts = []; + this._entry = null; this._stepRuns = null; this._resultReads = null; this._argArrayRegions = null; @@ -23838,6 +24034,7 @@ this.fallbackReason = null; this._executor = void 0; this._fusionDisabled = false; + this._threadsDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -23853,14 +24050,14 @@ } if (this._executor === void 0) this._prepareExecutor(sampled); if (this._executor) try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); if (e.recompilable) { this._prepareExecutor(sampled); if (this._executor) try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -23873,6 +24070,13 @@ this._tail = promise.then(noop, noop); return promise; } + _guardAsync(result) { + if (result && typeof result.then === "function") return result.then(null, error => { + this._dropExecutor(); + throw error; + }); + return result; + } setConstants(constants) { this.constants = Object.assign({}, constants || {}); const release = () => { @@ -23887,6 +24091,7 @@ const index = this.gpu.pipelines.indexOf(this); if (index !== -1) this.gpu.pipelines.splice(index, 1); } + if (this._executor && typeof this._executor.abortRuns === "function") this._executor.abortRuns(new Error(MSG_DESTROYED)); const release = () => { this._releasePlan(); }; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index e061c4cc..a0b7af11 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:04:04 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage({type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),o=["Array","Input","Number","Float","Integer","Boolean"];var u=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,c)).join(",");let d=r.get(p);if(!d){let e;if(i[u.kernel]){const t=this.pipeline._cloneKernel(l.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[u.kernel]=!0,e=l.clone.kernel;this._prepareKernel(e,h),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}a[n]=d,o[n]=h}for(let e=0;e{const t=l;return l=(e=>16*Math.ceil(e/16))(l+e),t},c=new Map,p=new Map,d=new Map,f=[],m=[],g=[],y=new Array(t.steps.length);for(let e=0;e${i}`;let l=S.get(u);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:v},o=b[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,o,!1);null===this.memory&&(this.memory=new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Instance(new WebAssembly.Module(h.bytes),c);l={run:p.exports.run,runSimd:p.exports.run_simd||null},S.set(u,l)}T[e]={run:l.run,runSimd:l.runSimd,cells:b[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=b[t.steps[e].outputBuffer],n=a[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=T,this._argArrayRegions=c,this._argScalarSlots=p,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),a.dispatchSpans(t.run,t.runSimd,t.cells,t.sizeX,0|s)}const i=this.plan.results,o=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._executor.execute(t)}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32;Atomics.store(s,t.genIndex,0),Atomics.store(s,t.countIndex,0);const r=this._stepRuns.map(e=>this._drawSeed(e)),n=this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:0,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(n).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)};let u=Atomics.load(t,s),l=Date.now();const h=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)o(n);else{if(a!==u)u=a,l=Date.now();else if(Date.now()-l>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(h):Promise.resolve().then(h)}else setTimeout(h,1)}};h()})}_abort(e){this._abortError||(this._abortError=e||new Error("pipeline threaded run aborted"),this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)))}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/backend/web-assembly/pipeline-executor.js b/src/backend/web-assembly/pipeline-executor.js index ebbcb85e..c319d7e4 100644 --- a/src/backend/web-assembly/pipeline-executor.js +++ b/src/backend/web-assembly/pipeline-executor.js @@ -1,19 +1,39 @@ const { utils } = require('../../utils'); const { Input } = require('../../input'); const { WebAssemblyKernel } = require('./kernel'); +const { WebAssemblyWorkerPool } = require('./worker-pool'); /** * Fused pipeline execution (docs/design/pipeline-compilation.md): every plan * step compiles to a wasm module over ONE shared memory laid out - * `[ pipeline args | literals | constants | plan buffers ]`, with each - * module's input/output offsets baked against that layout. Steps then run - * back-to-back synchronously; intermediates never leave wasm memory between - * passes — per call there is one flattenTo per pipeline argument and one - * readback per result, however many steps the plan unrolls to. + * `[ barrier control | pipeline args | literals | constants | plan buffers ]` + * (the control words exist only on the threaded path), with each module's + * input/output offsets baked against that layout. Per call there is one + * flattenTo per pipeline argument and one readback per result, however many + * steps the plan unrolls to. + * + * Sync path ('fused-sync'): steps run back-to-back on the calling thread. + * + * Threaded path ('fused-threaded'): when wasm threads exist and the plan is + * big enough, pool workers execute the WHOLE plan — each worker owns a + * contiguous cell-range slice of every step and advances step-to-step on an + * Atomics barrier (generation counter in the shared memory). The main thread + * dispatches once per call and then waits only for the final generation, so + * step boundaries cost no main-thread round trip. Threads unavailable or the + * plan too small falls back to the sync path; anything the backend cannot + * take at all degrades to the generic executor as usual. */ const SUPPORTED_VALUE_TYPES = ['Array', 'Input', 'Number', 'Float', 'Integer', 'Boolean']; +// the kernel's own threading floor (kernel.js _threadable): below this many +// cells in the largest step, splitting cannot beat the dispatch overhead +const THREAD_MIN_CELLS = 4096; + +// worker-side instance caches key on the entry id; the prefix keeps pipeline +// ids out of the kernel entry id space (see worker-pool _ensureSetup) +let nextPipelineEntryId = 1; + /** * The degradation signal, per the backend's usual contract: the pipeline * catches it and runs the generic executor with this reason. `recompilable` @@ -77,10 +97,18 @@ class WebAssemblyPipelineExecutor { this.gpu = pipeline.gpu; this.plan = plan; this.kind = 'fused-sync'; + this.threaded = false; this.destroyed = false; this.memory = null; this.f32 = null; this.i32 = null; + this.pool = null; + // a stalled barrier is a hang without this: reject when the generation + // counter makes no progress for this long (per step, not per run, so + // arbitrarily long plans stay legal as long as steps keep landing) + this.sanityTimeoutMs = 10000; + this._entry = null; + this._abortError = null; this._stepRuns = null; this._argArrayRegions = null; this._argScalarSlots = null; @@ -149,6 +177,31 @@ class WebAssemblyPipelineExecutor { offset = align16(offset + bytes); return at; }; + // the threaded decision precedes every allocation: the barrier control + // words must open the layout, and sharedness is a compile-time property + // of the memory import every step module declares + let threadWorkerCount = 0; + let controlOffset = -1; + if (!this.pipeline._threadsDisabled && WebAssemblyKernel.isThreadsSupported) { + let maxCells = 0; + for (let i = 0; i < plan.steps.length; i++) { + const output = plan.steps[i].output; + let cells = 1; + for (let d = 0; d < output.length; d++) cells *= output[d]; + if (cells > maxCells) maxCells = cells; + } + const pool = new WebAssemblyWorkerPool(); + threadWorkerCount = Math.min(pool.size, Math.ceil(maxCells / THREAD_MIN_CELLS)); + if (threadWorkerCount > 1) { + this.threaded = true; + this.kind = 'fused-threaded'; + this.pool = pool; + controlOffset = alloc(12); + } else { + // constructed but never spawned a worker; destroy only sets a flag + pool.destroy(); + } + } const argArrayRegions = new Map(); const argScalarSlots = new Map(); const literalArrayRegions = new Map(); @@ -241,6 +294,8 @@ class WebAssemblyPipelineExecutor { // loop lands on two instances however many steps it unrolled to const moduleCache = new Map(); const stepRuns = new Array(plan.steps.length); + const threadModules = []; + const threadModuleImports = []; for (let i = 0; i < plan.steps.length; i++) { const program = stepPrograms[i]; const kernel = program.kernel; @@ -262,9 +317,11 @@ class WebAssemblyPipelineExecutor { totalBytes, }; const cells = bufferRegions[plan.steps[i].outputBuffer].cells; - const assembled = kernel._assembleModule(layout, cells, false); + const assembled = kernel._assembleModule(layout, cells, this.threaded); if (this.memory === null) { - this.memory = new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum }); + this.memory = this.threaded ? + new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum, shared: true }) : + new WebAssembly.Memory({ initial: assembled.initial, maximum: assembled.maximum }); this.f32 = new Float32Array(this.memory.buffer); this.i32 = new Int32Array(this.memory.buffer); } @@ -272,22 +329,69 @@ class WebAssemblyPipelineExecutor { for (const name of kernel.usedMathImports) { imports.env['math_' + name] = Math[name]; } - const instance = new WebAssembly.Instance(new WebAssembly.Module(assembled.bytes), imports); + const module = new WebAssembly.Module(assembled.bytes); + const instance = new WebAssembly.Instance(module, imports); compiled = { run: instance.exports.run, runSimd: instance.exports.run_simd || null, + // what a worker needs to re-instantiate this module over the + // shared memory: the Module structured-clones, the import names + // rebuild the env + moduleIndex: threadModules.length, }; + threadModules.push(module); + threadModuleImports.push(Array.from(kernel.usedMathImports).sort()); moduleCache.set(moduleKey, compiled); } stepRuns[i] = { run: compiled.run, runSimd: compiled.runSimd, + moduleIndex: compiled.moduleIndex, cells: bufferRegions[plan.steps[i].outputBuffer].cells, sizeX: kernel.threadDim[0], usesRandom: kernel.usesRandom, randomSeed: kernel.randomSeed, }; } + if (this.threaded) { + // per-(worker, step) cell ranges are static — shapes are baked — so + // they compute once and ride every run message. The split matches the + // kernel's threaded contract: contiguous chunks, starts aligned down + // to a multiple of 4 so every worker can enter run_simd, last worker + // absorbs the tail; a worker idle for a small step still owns an + // (empty) range because the barrier fills only at workerCount arrivals + const workerRanges = []; + for (let w = 0; w < threadWorkerCount; w++) { + const ranges = new Array(plan.steps.length * 2); + for (let i = 0; i < plan.steps.length; i++) { + const cells = stepRuns[i].cells; + let chunk = Math.ceil(cells / threadWorkerCount) & ~3; + if (chunk < 4) chunk = 4; + const start = w * chunk; + if (start >= cells) { + ranges[i * 2] = 0; + ranges[i * 2 + 1] = 0; + } else { + ranges[i * 2] = start; + ranges[i * 2 + 1] = w === threadWorkerCount - 1 ? cells : Math.min(start + chunk, cells); + } + } + workerRanges.push(ranges); + } + this._entry = { + id: 'pipeline:' + nextPipelineEntryId++, + pipeline: true, + memory: this.memory, + modules: threadModules, + moduleMathImports: threadModuleImports, + steps: stepRuns.map(stepRun => ({ module: stepRun.moduleIndex, sizeX: stepRun.sizeX })), + countIndex: controlOffset / 4, + genIndex: controlOffset / 4 + 1, + abortIndex: controlOffset / 4 + 2, + workerCount: threadWorkerCount, + workerRanges, + }; + } for (let i = 0; i < uploadArrays.length; i++) { const upload = uploadArrays[i]; utils.flattenTo( @@ -418,13 +522,19 @@ class WebAssemblyPipelineExecutor { /** * @param {Array} args - sampled pipeline arguments - * @returns {*} results shaped per the plan; synchronous — the pipeline's - * tail promise provides the async contract + * @returns {*} results shaped per the plan; synchronous on the sync path + * (the pipeline's tail promise provides the async contract), a Promise on + * the threaded path */ execute(args) { if (this.destroyed) { throw new Error('pipeline fused executor has been destroyed'); } + if (this._abortError) { + // an aborted run leaves the barrier state unusable; the pipeline drops + // this executor on that rejection, so reuse is a caller bug + throw this._abortError; + } this._checkArguments(args); const f32 = this.f32; for (const [index, region] of this._argArrayRegions) { @@ -437,18 +547,139 @@ class WebAssemblyPipelineExecutor { for (const slot of this._argScalarSlots.values()) { this._writeScalar(slot, args[slot.index]); } + if (this.threaded) { + return this._executeThreaded(args); + } const stepRuns = this._stepRuns; for (let i = 0; i < stepRuns.length; i++) { const stepRun = stepRuns[i]; - let seed = 0; - if (stepRun.usesRandom) { - seed = stepRun.randomSeed !== null ? - (stepRun.randomSeed >>> 0) : - ((Math.random() * 0x100000000) >>> 0); - } - WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, seed | 0); + WebAssemblyKernel.dispatchSpans(stepRun.run, stepRun.runSimd, stepRun.cells, stepRun.sizeX, this._drawSeed(stepRun)); } - // the one readback: slice copies results out of wasm memory only here + return this._readResults(args); + } + + _drawSeed(stepRun) { + if (!stepRun.usesRandom) return 0; + return (stepRun.randomSeed !== null ? + (stepRun.randomSeed >>> 0) : + ((Math.random() * 0x100000000) >>> 0)) | 0; + } + + /** + * One pool dispatch for the whole plan; the workers walk every step over + * the already-written args and meet at the memory-resident barrier, so the + * only thing left to await here is the final generation. The pipeline tail + * serializes calls, which is what makes resetting the generation counter + * safe: no worker touches the control words between a run's final barrier + * and its next run message. + */ + _executeThreaded(args) { + const entry = this._entry; + const i32 = this.i32; + Atomics.store(i32, entry.genIndex, 0); + Atomics.store(i32, entry.countIndex, 0); + const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); + const finalGen = this._stepRuns.length; + const dispatched = this.pool.dispatchPipeline(entry, { baseGen: 0, seeds }); + // a dead worker rejects its task here; without the abort the surviving + // workers would sit on a barrier that can never fill + dispatched.then(null, error => this._abort(error)); + return this._waitForGeneration(finalGen).then(() => this._readResults(args)); + } + + /** + * Resolves when the generation counter reaches `target`, rejects on abort + * or when the counter stalls past sanityTimeoutMs. Atomics.waitAsync + * where the host has it (woken by the workers' notify and by _abort), + * short-slice polling otherwise — either way the main thread never blocks. + */ + _waitForGeneration(target) { + const i32 = this.i32; + const genIndex = this._entry.genIndex; + const waitAsync = typeof Atomics.waitAsync === 'function' ? Atomics.waitAsync : null; + return new Promise((resolve, reject) => { + // Atomics.waitAsync does not hold Node's event loop; if the workers' + // acks all land while the counter is short (a barrier gone wrong), + // nothing else would keep the process alive long enough for the + // sanity timeout to report it — so the wait pins the loop itself + const keepAlive = typeof setInterval === 'function' ? setInterval(() => {}, 200) : null; + const settle = (fn, value) => { + if (keepAlive !== null) clearInterval(keepAlive); + fn(value); + }; + let lastSeen = Atomics.load(i32, genIndex); + let lastProgress = Date.now(); + const check = () => { + if (this._abortError) { + settle(reject, this._abortError); + return; + } + const gen = Atomics.load(i32, genIndex); + if (gen >= target) { + settle(resolve); + return; + } + if (gen !== lastSeen) { + lastSeen = gen; + lastProgress = Date.now(); + } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { + const error = new Error( + `pipeline threaded barrier stalled at generation ${ gen } of ${ target } for ${ this.sanityTimeoutMs }ms`); + this._abort(error); + settle(reject, error); + return; + } + if (waitAsync) { + const slice = Math.max(1, Math.min(200, this.sanityTimeoutMs)); + const wait = waitAsync(i32, genIndex, gen, slice); + if (wait.async) { + wait.value.then(check); + } else { + // value already moved; a microtask hop keeps the recheck loop + // off the stack however many generations land back-to-back + Promise.resolve().then(check); + } + } else { + setTimeout(check, 1); + } + }; + check(); + }); + } + + /** + * Releases every wait on the run: workers poll the abort word at each + * barrier (and inside their sliced Atomics.wait), the main thread checks + * it on every generation wake. First cause wins; the executor is dead + * afterwards — the barrier count is indeterminate. + */ + _abort(error) { + if (this._abortError) return; + this._abortError = error || new Error('pipeline threaded run aborted'); + if (this.i32 && this._entry) { + Atomics.store(this.i32, this._entry.abortIndex, 1); + Atomics.notify(this.i32, this._entry.genIndex); + } + } + + /** + * Entry point for Pipeline.destroy() while a run may be in flight: the + * sync path cannot be mid-run (it never yields), so only the threaded + * path has anything to interrupt. + */ + abortRuns(error) { + if (this.threaded) { + this._abort(error); + } + } + + /** + * The one readback: slice copies results out of wasm memory only here. + * On the threaded path the barrier's final generation happened-before + * this read, so the workers' stores are visible. + */ + _readResults(args) { + const f32 = this.f32; const results = this.plan.results; const values = new Array(this._resultReads.length); for (let i = 0; i < this._resultReads.length; i++) { @@ -474,6 +705,14 @@ class WebAssemblyPipelineExecutor { destroy() { if (this.destroyed) return; this.destroyed = true; + if (this.pool) { + // wake anything still waiting before the views go: workers exit their + // barriers and ack, the pool rejects whatever is left, and terminate + // drops the workers' hold on the shared memory + this._abort(new Error('pipeline fused executor has been destroyed')); + this.pool.destroy(); + this.pool = null; + } const gpuKernels = this.gpu && this.gpu.kernels; for (let i = 0; i < this._extraShortcuts.length; i++) { const shortcut = this._extraShortcuts[i]; @@ -484,6 +723,7 @@ class WebAssemblyPipelineExecutor { } } this._extraShortcuts = []; + this._entry = null; this._stepRuns = null; this._resultReads = null; this._argArrayRegions = null; diff --git a/src/backend/web-assembly/worker-pool.js b/src/backend/web-assembly/worker-pool.js index 1410444d..7a757280 100644 --- a/src/backend/web-assembly/worker-pool.js +++ b/src/backend/web-assembly/worker-pool.js @@ -34,9 +34,19 @@ function defaultConcurrency() { * x-row, so run_simd is used only when the row width is a multiple of 4 (a * 4-aligned range start then lands every quad inside one row); other shapes * take the scalar export, which is bit-identical by the SIMD contract. + * + * Pipeline entries ('pipelineSetup'/'pipelineRun') execute a WHOLE fused + * plan per task: every step module is instantiated over the plan's shared + * memory once at setup, then one run message walks all steps with an + * Atomics barrier between them — a generation counter in the shared memory, + * so step boundaries cost no postMessage round trip. Waits are sliced to + * 100ms so a barrier that can never fill (a peer died) is escapable: the + * main thread sets the abort word and notifies the generation word, and + * every check of either releases the worker to ack and go idle. */ const WORKER_SOURCE = ` var entries = {}; +var pipelines = {}; function handleMessage(message, post) { if (message.type === 'setup') { var imports = { env: { memory: message.memory } }; @@ -50,8 +60,36 @@ function handleMessage(message, post) { sizeX: message.sizeX }; post({ type: 'ready', id: message.id }); + } else if (message.type === 'pipelineSetup') { + var instances = []; + for (var i = 0; i < message.modules.length; i++) { + var imports = { env: { memory: message.memory } }; + var math = message.moduleMathImports[i]; + for (var j = 0; j < math.length; j++) { + imports.env['math_' + math[j]] = Math[math[j]]; + } + instances.push(new WebAssembly.Instance(message.modules[i], imports)); + } + var steps = []; + for (var i = 0; i < message.steps.length; i++) { + var exported = instances[message.steps[i].module].exports; + steps.push({ + run: exported.run, + runSimd: exported.run_simd || null, + sizeX: message.steps[i].sizeX + }); + } + pipelines[message.id] = { + steps: steps, + i32: new Int32Array(message.memory.buffer), + countIndex: message.countIndex, + genIndex: message.genIndex, + abortIndex: message.abortIndex + }; + post({ type: 'ready', id: message.id }); } else if (message.type === 'release') { delete entries[message.id]; + delete pipelines[message.id]; } else if (message.type === 'run') { var entry = entries[message.id]; var start = message.start; @@ -65,6 +103,46 @@ function handleMessage(message, post) { entry.run(start, end, seed); } post({ type: 'done', taskId: message.taskId }); + } else if (message.type === 'pipelineRun') { + var pipeline = pipelines[message.id]; + var i32 = pipeline.i32; + var gen = message.baseGen; + var aborted = false; + for (var s = 0; s < pipeline.steps.length && !aborted; s++) { + if (Atomics.load(i32, pipeline.abortIndex)) { + aborted = true; + break; + } + var step = pipeline.steps[s]; + var start = message.ranges[s * 2]; + var end = message.ranges[s * 2 + 1]; + var seed = message.seeds[s]; + if (end > start) { + if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) { + var quadEnd = end - ((end - start) & 3); + if (quadEnd > start) step.runSimd(start, quadEnd, seed); + if (quadEnd < end) step.run(quadEnd, end, seed); + } else { + step.run(start, end, seed); + } + } + gen++; + if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) { + Atomics.store(i32, pipeline.countIndex, 0); + Atomics.store(i32, pipeline.genIndex, gen); + Atomics.notify(i32, pipeline.genIndex); + } else { + for (;;) { + if (Atomics.load(i32, pipeline.genIndex) >= gen) break; + if (Atomics.load(i32, pipeline.abortIndex)) { + aborted = true; + break; + } + Atomics.wait(i32, pipeline.genIndex, gen - 1, 100); + } + } + } + post({ type: 'done', taskId: message.taskId, aborted: aborted }); } } if (typeof self !== 'undefined' && typeof postMessage === 'function') { @@ -225,7 +303,11 @@ class WebAssemblyWorkerPool { /** * One setup message per (worker, entry) — concurrent tasks for the same - * entry share the in-flight ready wait rather than re-sending the module + * entry share the in-flight ready wait rather than re-sending the module. + * Kernel entries and pipeline entries share this bookkeeping (a pool is + * owned by exactly one kernel or one pipeline executor, and pipeline ids + * are string-prefixed, so the id spaces cannot collide); only the setup + * message shape differs. */ _ensureSetup(worker, entry) { if (worker.state.setup.has(entry.id)) return Promise.resolve(); @@ -238,7 +320,17 @@ class WebAssemblyWorkerPool { }); worker.state.settingUp.set(entry.id, wait); this._updateRef(worker); - worker.handle.postMessage({ + worker.handle.postMessage(entry.pipeline ? { + type: 'pipelineSetup', + id: entry.id, + memory: entry.memory, + modules: entry.modules, + moduleMathImports: entry.moduleMathImports, + steps: entry.steps, + countIndex: entry.countIndex, + genIndex: entry.genIndex, + abortIndex: entry.abortIndex, + } : { type: 'setup', id: entry.id, module: entry.module, @@ -286,6 +378,52 @@ class WebAssemblyWorkerPool { return Promise.all(runs).then(() => undefined); } + /** + * One task per worker for a WHOLE fused plan: the barrier between steps + * lives in the entry's shared memory, so this is the only postMessage + * round trip a pipeline call makes. Every worker in [0, workerCount) must + * receive its task — the barrier fills only at workerCount arrivals — and + * a worker that dies rejects its task through the pool's usual machinery, + * which is the caller's signal to set the entry's abort word. + * @param {Object} entry pipeline entry: {id, pipeline, memory, modules, + * moduleMathImports, steps, countIndex, genIndex, abortIndex, workerCount, + * workerRanges} + * @param {Object} run per-call inputs: {baseGen, seeds} + * @returns {Promise} resolves when every worker has acked its walk + * of the plan + */ + dispatchPipeline(entry, run) { + if (this.destroyed) return Promise.reject(new Error('WebAssembly worker pool has been destroyed')); + this.dispatchCount++; + this.lastDispatch = { + workerCount: entry.workerCount, + ranges: entry.workerRanges.map(ranges => ranges.slice()), + }; + const runs = []; + for (let index = 0; index < entry.workerCount; index++) { + const worker = this._worker(index); + runs.push(this._ensureSetup(worker, entry).then(() => new Promise((resolve, reject) => { + if (worker.dead) { + reject(new Error('WebAssembly worker died before the task could run')); + return; + } + const taskId = ++this._taskId; + worker.state.pending.set(taskId, { resolve, reject }); + this._updateRef(worker); + worker.handle.postMessage({ + type: 'pipelineRun', + id: entry.id, + taskId, + ranges: entry.workerRanges[index], + seeds: run.seeds, + baseGen: run.baseGen, + workerCount: entry.workerCount, + }); + }))); + } + return Promise.all(runs).then(() => undefined); + } + /** * Drops an entry's instantiation from every live worker: the worker-side * instances are what keep an evicted entry's shared memory alive (#870). diff --git a/src/index.d.ts b/src/index.d.ts index c39da89d..255f5b0a 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -420,7 +420,8 @@ export interface IPipelineRunShortcut { /** * 'generic' runs step-by-step through the normal kernel machinery on every * backend; 'fused-sync' runs every step over one shared wasm memory on the - * webasm backend + * webasm backend; 'fused-threaded' has pool workers walk the whole plan + * over that memory on an Atomics barrier */ readonly executorKind: string; /** why the fused executor declined this plan; null while fused */ diff --git a/src/pipeline.js b/src/pipeline.js index 033794de..cee46463 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -255,7 +255,8 @@ class Pipeline { * executor identity probe for tests and later phases: 'generic' executes * step-by-step through the normal kernel machinery on every backend; * 'fused-sync' is the webasm executor running every step over one shared - * wasm memory + * wasm memory; 'fused-threaded' is that executor with pool workers + * walking the whole plan on an Atomics barrier * @type {String} */ this.executorKind = 'generic'; @@ -272,6 +273,8 @@ class Pipeline { this._executor = undefined; /** test/benchmark hook: forces the generic executor when true */ this._fusionDisabled = false; + /** test/benchmark hook: keeps a fused executor off the worker pool */ + this._threadsDisabled = false; this.destroyed = false; /** * concurrent calls to one pipeline serialize on this tail, the same @@ -303,7 +306,7 @@ class Pipeline { } if (this._executor) { try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); @@ -313,7 +316,7 @@ class Pipeline { this._prepareExecutor(sampled); if (this._executor) { try { - return this._executor.execute(sampled); + return this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -331,6 +334,25 @@ class Pipeline { return promise; } + /** + * The threaded executor rejects asynchronously (worker death, stalled + * barrier, destroy mid-run); any such failure leaves its barrier state + * unusable, so the executor is dropped and the next call compiles a + * fresh one. Fallback decisions stay synchronous — the signature check + * throws before dispatch — so a FusionFallback can never surface here. + * @param {*} result - executor.execute's return: a value (sync) or a + * Promise (threaded) + */ + _guardAsync(result) { + if (result && typeof result.then === 'function') { + return result.then(null, error => { + this._dropExecutor(); + throw error; + }); + } + return result; + } + /** * @desc Trace-time constants change: the plan is invalid, the next call * re-traces. The release queues behind in-flight calls so their buffers @@ -360,6 +382,13 @@ class Pipeline { this.gpu.pipelines.splice(index, 1); } } + // a threaded run in flight must reject now, not finish first: its + // workers hold the shared memory, and a barrier mid-plan could outlive + // any deadline the caller has. The rejection settles the tail, which is + // what lets the queued release below run at all. + if (this._executor && typeof this._executor.abortRuns === 'function') { + this._executor.abortRuns(new Error(MSG_DESTROYED)); + } const release = () => { this._releasePlan(); }; diff --git a/test/all.html b/test/all.html index 0aebb8e8..35998a5f 100644 --- a/test/all.html +++ b/test/all.html @@ -311,6 +311,7 @@ + diff --git a/test/features/pipeline/threaded-webasm.js b/test/features/pipeline/threaded-webasm.js new file mode 100644 index 00000000..5c6415ef --- /dev/null +++ b/test/features/pipeline/threaded-webasm.js @@ -0,0 +1,395 @@ +const { assert, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline threaded webasm executor'); + +// The threaded executor hands the WHOLE plan to pool workers: each worker +// owns a cell-range slice of every step and advances step-to-step on an +// Atomics barrier in the shared memory, so a pipeline call costs one pool +// dispatch however many steps the plan unrolls to. Every scenario asserts +// executorKind === 'fused-threaded' so a silent fall back to the sync or +// generic executor fails the suite. Plans here are sized past the threading +// floor (4096 cells per worker) — on a single-core host these tests would +// see 'fused-sync' and fail, which is a deliberate canary, not flake. + +const N = 16384; + +function assertClose(assert, actual, expected, label) { + const values = Array.from(actual); + assert.equal(values.length, expected.length, `${ label }: length`); + let worst = 0; + for (let i = 0; i < values.length; i++) { + const delta = Math.abs(values[i] - expected[i]); + const scale = Math.max(Math.abs(expected[i]), 1); + worst = Math.max(worst, delta / scale); + } + assert.ok(worst <= 1e-5, `${ label }: worst relative delta ${ worst }`); +} + +function makeJacobi(gpu, sweeps) { + const sweep = gpu.createKernel(function (u, q) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + let right = this.thread.x + 1; + if (right > this.constants.n - 1) right = this.constants.n - 1; + return 0.25 * (u[left] + u[right]) + q[this.thread.x]; + }, { output: [N], constants: { n: N } }); + return gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps } }); +} + +function jacobiArgs(shift) { + const u0 = new Float32Array(N); + const q = new Float32Array(N); + for (let i = 0; i < N; i++) { + u0[i] = (i + shift) % 7; + q[i] = ((i + shift) % 3) * 0.5; + } + return [u0, q]; +} + +test('big jacobi ping-pong runs fused-threaded and matches the cpu reference', async assert => { + const webasm = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = makeJacobi(webasm, 12); + const reference = makeJacobi(cpu, 12); + for (let call = 0; call < 3; call++) { + const args = jacobiArgs(call * 5); + const out = await solve.apply(null, args); + const expected = await reference.apply(null, args); + assertClose(assert, out, Array.from(expected), `call ${ call }`); + } + assert.equal(solve.executorKind, 'fused-threaded', 'the plan crossed the threading floor'); + assert.equal(solve.fallbackReason, null, 'no fallback reason while threaded'); + webasm.destroy(); + cpu.destroy(); +}); + +test('2d chain runs fused-threaded and matches the cpu reference', async assert => { + const make = gpu => { + const blurX = gpu.createKernel(function (u) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + return 0.5 * (u[this.thread.y][this.thread.x] + u[this.thread.y][left]); + }, { output: [128, 128] }); + const scale = gpu.createKernel(function (u, k) { + return u[this.thread.y][this.thread.x] * k + this.thread.x; + }, { output: [128, 128] }); + return gpu.createPipeline(function (u, k) { + return scale(blurX(blurX(u)), k); + }); + }; + const webasm = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = make(webasm); + const reference = make(cpu); + const u0 = []; + for (let y = 0; y < 128; y++) { + const row = new Float32Array(128); + for (let x = 0; x < 128; x++) row[x] = (x * 31 + y * 7) % 13; + u0.push(row); + } + const out = await solve(u0, 3); + const expected = await reference(u0, 3); + for (let y = 0; y < 128; y++) { + assertClose(assert, out[y], Array.from(expected[y]), `row ${ y }`); + } + assert.equal(solve.executorKind, 'fused-threaded'); + webasm.destroy(); + cpu.destroy(); +}); + +// The barrier-correctness gauntlet: every step reads a cell HALFWAY across +// the array from the one it writes, so step s+1 consumes cells written by +// every worker's slice of step s — a missed fence surfaces as a stale read. +// All values are integers below 2^24, so f32 arithmetic is exact and any +// race shows up as a hard mismatch, not a tolerance question. Repeated runs +// shake scheduling: one pipeline hammered for many calls plus fresh +// pipelines whose worker startup timing differs. +test('cross-slice fence: step N+1 reads every slice of step N, repeatedly', async assert => { + const STEPS = 10; + const reference = u0 => { + let u = Array.from(u0); + for (let s = 0; s < STEPS; s++) { + const next = new Array(N); + for (let i = 0; i < N; i++) { + let j = i + N / 2; + if (j >= N) j -= N; + next[i] = u[i] + u[j]; + } + u = next; + } + return u; + }; + const makeFence = gpu => { + const fold = gpu.createKernel(function (u) { + let j = this.thread.x + this.constants.half; + if (j >= this.constants.n) j -= this.constants.n; + return u[this.thread.x] + u[j]; + }, { output: [N], constants: { n: N, half: N / 2 } }); + return gpu.createPipeline(function (u) { + for (let s = 0; s < this.constants.steps; s++) { + u = fold(u); + } + return u; + }, { constants: { steps: STEPS } }); + }; + const inputs = iteration => { + const u0 = new Float32Array(N); + for (let i = 0; i < N; i++) u0[i] = (i + iteration) % 17; + return u0; + }; + const verify = (out, expected, label) => { + for (let i = 0; i < N; i++) { + if (out[i] !== expected[i]) { + assert.equal(out[i], expected[i], `${ label }: first mismatch at cell ${ i }`); + return false; + } + } + return true; + }; + const gpu = new GPU({ mode: 'webasm' }); + const hammered = makeFence(gpu); + let clean = true; + for (let iteration = 0; iteration < 20 && clean; iteration++) { + const u0 = inputs(iteration); + clean = verify(await hammered(u0), reference(u0), `warm iteration ${ iteration }`); + } + assert.equal(hammered.executorKind, 'fused-threaded'); + for (let cold = 0; cold < 5 && clean; cold++) { + const fresh = makeFence(gpu); + const u0 = inputs(100 + cold); + clean = verify(await fresh(u0), reference(u0), `cold pipeline ${ cold }`); + assert.equal(fresh.executorKind, 'fused-threaded', `cold pipeline ${ cold } threaded`); + await fresh.destroy(); + } + assert.ok(clean, '25 iterations bit-exact across the barrier'); + gpu.destroy(); +}); + +test('plans under the threading floor stay fused-sync', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [64] }); + const solve = gpu.createPipeline(function (u) { + return inc(inc(u)); + }); + const out = await solve(new Float32Array(64).fill(1)); + assert.equal(out[0], 3); + assert.equal(solve.executorKind, 'fused-sync', 'a 64-cell plan is not worth a worker pool'); + gpu.destroy(); +}); + +test('_threadsDisabled keeps a big plan on the sync path', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const solve = makeJacobi(gpu, 4); + solve.pipeline._threadsDisabled = true; + const args = jacobiArgs(0); + const out = await solve.apply(null, args); + assert.equal(out.length, N); + assert.equal(solve.executorKind, 'fused-sync', 'threads unavailable falls back to sync fusion'); + gpu.destroy(); +}); + +test('non-multiple-of-4 width takes the scalar worker path correctly', async assert => { + const M = 8190; + const make = gpu => { + const sweep = gpu.createKernel(function (u) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + return u[this.thread.x] * 0.5 + u[left]; + }, { output: [M] }); + return gpu.createPipeline(function (u) { + return sweep(sweep(sweep(u))); + }); + }; + const webasm = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const u0 = new Float32Array(M); + for (let i = 0; i < M; i++) u0[i] = i % 11; + const out = await make(webasm)(u0); + const expected = await make(cpu)(u0); + assertClose(assert, out, Array.from(expected), 'scalar-path results'); + webasm.destroy(); + cpu.destroy(); +}); + +test('one pool dispatch per call; worker slices tile every step exactly', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const solve = makeJacobi(gpu, 32); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.executorKind, 'fused-threaded'); + const executor = solve.pipeline._executor; + const pool = executor.pool; + const before = pool.dispatchCount; + await solve.apply(null, args); + await solve.apply(null, args); + assert.equal(pool.dispatchCount - before, 2, + 'a 32-step plan costs ONE dispatch per call — step boundaries make no main-thread round trip'); + const entry = executor._entry; + assert.equal(pool.lastDispatch.workerCount, entry.workerCount, 'every barrier participant got its task'); + assert.ok(entry.workerCount >= 2, 'the plan actually split'); + const stepCount = solve.plan.steps.length; + assert.equal(entry.workerRanges[0].length, stepCount * 2, 'a range per worker per step'); + let violations = 0; + for (let s = 0; s < stepCount; s++) { + const spans = []; + for (let w = 0; w < entry.workerCount; w++) { + const start = entry.workerRanges[w][s * 2]; + const end = entry.workerRanges[w][s * 2 + 1]; + if (end > start) spans.push([start, end]); + } + spans.sort((a, b) => a[0] - b[0]); + let cursor = 0; + for (let i = 0; i < spans.length; i++) { + if (spans[i][0] !== cursor) violations++; + cursor = spans[i][1]; + } + if (cursor !== N) violations++; + } + assert.equal(violations, 0, 'every step tiles [0, cells) with no gap or overlap'); + gpu.destroy(); +}); + +test('concurrent calls serialize on the tail with per-call arguments', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = makeJacobi(gpu, 8); + const reference = makeJacobi(cpu, 8); + const argSets = [jacobiArgs(1), jacobiArgs(2), jacobiArgs(3)]; + const outs = await Promise.all(argSets.map(args => solve.apply(null, args))); + for (let i = 0; i < argSets.length; i++) { + const expected = await reference.apply(null, argSets[i]); + assertClose(assert, outs[i], Array.from(expected), `concurrent call ${ i }`); + } + assert.equal(solve.executorKind, 'fused-threaded'); + gpu.destroy(); + cpu.destroy(); +}); + +test('argument size drift recompiles and stays threaded', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = makeJacobi(gpu, 6); + const reference = makeJacobi(cpu, 6); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.executorKind, 'fused-threaded'); + // longer input: the kernel still reads [0, N) but the arg region resizes + const grown = [new Float32Array(N + 512), args[1]]; + grown[0].set(args[0]); + const out = await solve.apply(null, grown); + const expected = await reference.apply(null, grown); + assertClose(assert, out, Array.from(expected), 'post-drift results'); + assert.equal(solve.executorKind, 'fused-threaded', 'recompiled threaded for the new signature'); + gpu.destroy(); + cpu.destroy(); +}); + +test('setConstants re-traces and the new plan threads again', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = makeJacobi(gpu, 4); + const reference = makeJacobi(cpu, 4); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.plan.steps.length, 4); + solve.setConstants({ sweeps: 9, n: N }); + reference.setConstants({ sweeps: 9, n: N }); + const out = await solve.apply(null, args); + const expected = await reference.apply(null, args); + assertClose(assert, out, Array.from(expected), 're-traced results'); + assert.equal(solve.plan.steps.length, 9, 'the re-traced plan has the new sweep count'); + assert.equal(solve.executorKind, 'fused-threaded'); + gpu.destroy(); + cpu.destroy(); +}); + +test('Math.random draws a fresh seed per call across the pool', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const noise = gpu.createKernel(function () { + return Math.random(); + }, { output: [8192] }); + const solve = gpu.createPipeline(function () { + return noise(); + }); + const first = await solve(); + const second = await solve(); + assert.equal(solve.executorKind, 'fused-threaded'); + let inRange = true; + let identical = true; + for (let i = 0; i < 8192; i++) { + if (first[i] < 0 || first[i] >= 1 || second[i] < 0 || second[i] >= 1) inRange = false; + if (first[i] !== second[i]) identical = false; + } + assert.ok(inRange, 'every draw in [0, 1)'); + assert.notOk(identical, 'an unseeded kernel reseeds per call, threaded or not'); + gpu.destroy(); +}); + +test('a dead worker rejects the run cleanly and the next call recovers', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const cpu = new GPU({ mode: 'cpu' }); + const solve = makeJacobi(gpu, 400); + const reference = makeJacobi(cpu, 400); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.executorKind, 'fused-threaded'); + const pool = solve.pipeline._executor.pool; + const doomed = solve.apply(null, args); + // killed before the 400-step walk can finish: the barrier the survivors + // are sitting on can never fill, and the run must reject, not hang + pool.workers[0].handle.terminate(); + await assert.rejects(doomed, /worker/i, 'the in-flight run rejected with the worker death'); + const out = await solve.apply(null, args); + const expected = await reference.apply(null, args); + assertClose(assert, out, Array.from(expected), 'recovered results'); + assert.equal(solve.executorKind, 'fused-threaded', 'a fresh executor threads again'); + gpu.destroy(); + cpu.destroy(); +}); + +test('a barrier that can never fill trips the sanity timeout, not a hang', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const solve = makeJacobi(gpu, 16); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.executorKind, 'fused-threaded'); + const executor = solve.pipeline._executor; + executor.sanityTimeoutMs = 250; + // one worker's run message silently vanishes — no death, no rejection + // from the pool, exactly the failure the progress timeout exists for + const worker = executor.pool._worker(executor._entry.workerCount - 1); + const originalPost = worker.handle.postMessage.bind(worker.handle); + worker.handle.postMessage = message => { + if (message.type === 'pipelineRun') return; + originalPost(message); + }; + await assert.rejects(solve.apply(null, args), /stalled/, 'the stall rejected with the barrier diagnosis'); + const out = await solve.apply(null, args); + assert.equal(out.length, N, 'a fresh executor and pool recovered'); + assert.equal(solve.executorKind, 'fused-threaded'); + gpu.destroy(); +}); + +test('destroy mid-run rejects the in-flight call cleanly', async assert => { + const gpu = new GPU({ mode: 'webasm' }); + const solve = makeJacobi(gpu, 2000); + const args = jacobiArgs(0); + await solve.apply(null, args); + assert.equal(solve.executorKind, 'fused-threaded'); + const inFlight = solve.apply(null, args); + // past the tail and into the worker walk before destroy lands + await new Promise(resolve => setTimeout(resolve, 15)); + const destroyed = solve.destroy(); + await assert.rejects(inFlight, /destroyed/, 'the in-flight run rejected instead of finishing the plan'); + await destroyed; + await assert.rejects(solve.apply(null, args), /destroyed/, 'later calls reject too'); + gpu.destroy(); +}); From d81437a9f438d883c1681d3538f4458b5c66f520 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 13:34:44 +0800 Subject: [PATCH 04/16] bench: pipeline vs per-pass chaining on the gauntlet jacobi/heat rows Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- scripts/benchmark-pipeline.mjs | 340 +++++++++++++++++++++++++++++++++ 1 file changed, 340 insertions(+) create mode 100644 scripts/benchmark-pipeline.mjs diff --git a/scripts/benchmark-pipeline.mjs b/scripts/benchmark-pipeline.mjs new file mode 100644 index 00000000..8abc9dc6 --- /dev/null +++ b/scripts/benchmark-pipeline.mjs @@ -0,0 +1,340 @@ +#!/usr/bin/env node +// Benchmarks createPipeline against today's per-pass kernel chaining on the +// gauntlet's two iterative-stencil workloads, in plain Node. Prints a +// GitHub-markdown table plus raw JSON to stdout. +// +// node scripts/benchmark-pipeline.mjs +// +// The workloads are the gpu.rocks gauntlet's jacobi and heat rows — same +// make(), same fp32-exact constants, same index-weighted checksums, same +// hand-tuned flat-buffer plain-JS oracle — copied here rather than imported +// so the benchmark does not reach outside this repo. Methodology follows +// the gauntlet runner: +// - every mode's checksum is validated against the oracle (relative 1e-3) +// before timing; a mismatch aborts the run +// - pipeline rows additionally assert executorKind after the validation +// call, so a silent fallback can never be benchmarked under its label +// - median of up to 5 runs; once a single run exceeds 2 s the loop is +// capped at the next run +// - every run starts from the pristine grid (the oracle re-copies u0, the +// per-pass row re-reads its resident u0 texture, the pipeline re-samples +// its arguments), so no run inherits a prior run's relaxation +// +// Cost accounting is deliberately tilted against the pipeline: the per-pass +// row uploads its inputs ONCE at build (the gauntlet's contract — a real +// solver uploads its problem once) while pipeline rows pay the argument +// snapshot + upload on EVERY call, because that is what a pipeline call +// costs. Speedups in the table are relative to the per-pass row, which is +// the number the design contract's acceptance bar is written against. + +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const { GPU } = require('../src'); + +const N = 1024; + +function lcg(seed) { + let s = seed >>> 0; + return () => { + s = (s * 1664525 + 1013904223) >>> 0; + return (s >>> 8) / 0x1000000; + }; +} + +// Rows of a flat grid as a 2-D array, which is what a gpu.js kernel indexes. +// subarray, not slice: these are views, so nothing is copied here — the +// pipeline's own call-time snapshot is the copy being priced. +function rows(flat, n) { + const out = []; + for (let y = 0; y < n; y++) out.push(flat.subarray(y * n, y * n + n)); + return out; +} + +function relativeError(a, b) { + const denominator = Math.max(Math.abs(a), Math.abs(b), 1e-20); + return Math.abs(a - b) / denominator; +} + +// gpu.js hands back rows, the oracle hands back one flat array; both shapes +// are walked rather than flattened. Index-weighted so a backend that swept +// only part of the grid cannot match by luck. +function weightedSum(out, squared) { + let acc = 0; + if (ArrayBuffer.isView(out)) { + for (let i = 0; i < out.length; i++) { + const v = squared ? out[i] * out[i] : out[i]; + acc += v * (1 + (i % 17)); + } + } else { + for (let y = 0; y < out.length; y++) { + const row = out[y]; + for (let x = 0; x < row.length; x++) { + const v = squared ? row[x] * row[x] : row[x]; + acc += v * (1 + ((y * N + x) % 17)); + } + } + } + return acc / (N * N); +} + +const identitySource = function (v) { + return v[this.thread.y][this.thread.x]; +}; + +function jacobi() { + const SWEEPS = 512; + const HI = N - 2; + const C = (N - 1) / 2; // grid centre, exact in fp32 + const INV = Math.fround(2 / (N - 1)); + const QS = 1 / 1024; // power of two, exact everywhere + + const sweepSource = function (u, src) { + const x = this.thread.x; + const y = this.thread.y; + // Dirichlet edge, copied through — keeps both ping-pong buffers holding + // a correct edge without either being pre-filled + if (x < 1 || y < 1 || x > this.constants.hi || y > this.constants.hi) { + return u[y][x]; + } + return 0.25 * (u[y - 1][x] + u[y + 1][x] + u[y][x - 1] + u[y][x + 1]) + src[y][x]; + }; + + return { + name: `jacobi ${ N }×${ N }, ${ SWEEPS } sweeps`, + make() { + const rnd = lcg(0x27d4eb2f); + const u0 = new Float32Array(N * N); + const q = new Float32Array(N * N); + for (let y = 0; y < N; y++) { + const sy = (y - C) * INV; + for (let x = 0; x < N; x++) { + const sx = (x - C) * INV; + const i = y * N + x; + u0[i] = 0.5 + 0.25 * Math.sin(3 * Math.PI * sx) * Math.sin(2 * Math.PI * sy) + 0.1 * (rnd() - 0.5); + q[i] = QS * (2 - sx * sx - sy * sy); + } + } + return { u0, q }; + }, + js({ u0, q }) { + // copied, not aliased: both buffers get the boundary because both take + // a turn as the source + let src = new Float32Array(u0); + let dst = new Float32Array(u0); + for (let s = 0; s < SWEEPS; s++) { + for (let y = 1; y <= HI; y++) { + const row = y * N; + for (let x = 1; x <= HI; x++) { + const i = row + x; + dst[i] = 0.25 * (src[i - N] + src[i + N] + src[i - 1] + src[i + 1]) + q[i]; + } + } + const t = src; + src = dst; + dst = t; + } + return src; + }, + reduce(out) { + return weightedSum(out, false); + }, + async perPass(gpu, { u0, q }) { + // two instances of one kernel body: with immutable:false a kernel + // reuses its own output texture, so one instance cannot both read the + // previous sweep and overwrite it + const settings = { constants: { hi: HI }, output: [N, N], pipeline: true }; + const kA = gpu.createKernel(sweepSource, settings); + const kB = gpu.createKernel(sweepSource, settings); + // two identity uploads, not one called twice: the second call would + // hand back the texture it filled the first time + const upU = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const upQ = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const u0Tex = await upU(rows(u0, N)); + const qTex = await upQ(rows(q, N)); + return { + async run() { + // sweep 0 reads the pristine u0 texture and writes kA's own, so + // every run starts from the same grid + let t = u0Tex; + for (let s = 0; s < SWEEPS; s++) t = await (s % 2 === 0 ? kA : kB)(t, qTex); + return t.toArray ? await t.toArray() : t; + }, + }; + }, + buildPipeline(gpu, { u0, q }) { + // ONE kernel — double-buffering the ping-pong is the plan's business + const sweep = gpu.createKernel(sweepSource, { constants: { hi: HI }, output: [N, N] }); + const solve = gpu.createPipeline(function (u, src) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, src); + } + return u; + }, { constants: { sweeps: SWEEPS } }); + const uRows = rows(u0, N); + const qRows = rows(q, N); + return { shortcut: solve, run: () => solve(uRows, qRows) }; + }, + }; +} + +function heat() { + const STEPS = 1024; + const HI = N - 2; + const ALPHA = Math.fround(0.2); // rounded to fp32 once, shared by every column + + const stepSource = function (u) { + const x = this.thread.x; + const y = this.thread.y; + if (x < 1 || y < 1 || x > this.constants.hi || y > this.constants.hi) { + return u[y][x]; + } + const c = u[y][x]; + return c + this.constants.alpha * (u[y - 1][x] + u[y + 1][x] + u[y][x - 1] + u[y][x + 1] - 4 * c); + }; + + return { + name: `heat ${ N }×${ N }, ${ STEPS } steps`, + make() { + const rnd = lcg(0x1b873593); + const u0 = new Float32Array(N * N); + const k = (2 * Math.PI) / 32; // 32-cell wavelength the run annihilates + for (let y = 0; y < N; y++) { + const sy = Math.sin(k * y); + for (let x = 0; x < N; x++) { + u0[y * N + x] = 0.5 + 0.45 * Math.sin(k * x) * sy + 0.05 * (rnd() - 0.5); + } + } + return { u0 }; + }, + js({ u0 }) { + let src = new Float32Array(u0); + let dst = new Float32Array(u0); + for (let s = 0; s < STEPS; s++) { + for (let y = 1; y <= HI; y++) { + const row = y * N; + for (let x = 1; x <= HI; x++) { + const i = row + x; + const c = src[i]; + dst[i] = c + ALPHA * (src[i - N] + src[i + N] + src[i - 1] + src[i + 1] - 4 * c); + } + } + const t = src; + src = dst; + dst = t; + } + return src; + }, + // field energy: diffusion conserves the mean, so a mean-based checksum + // would pass a backend that did nothing; the sum of squares falls 17% + reduce(out) { + return weightedSum(out, true); + }, + async perPass(gpu, { u0 }) { + const settings = { constants: { hi: HI, alpha: ALPHA }, output: [N, N], pipeline: true }; + const kA = gpu.createKernel(stepSource, settings); + const kB = gpu.createKernel(stepSource, settings); + const upload = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const u0Tex = await upload(rows(u0, N)); + return { + async run() { + let t = u0Tex; + for (let s = 0; s < STEPS; s++) t = await (s % 2 === 0 ? kA : kB)(t); + return t.toArray ? await t.toArray() : t; + }, + }; + }, + buildPipeline(gpu, { u0 }) { + const step = gpu.createKernel(stepSource, { constants: { hi: HI, alpha: ALPHA }, output: [N, N] }); + const diffuse = gpu.createPipeline(function (u) { + for (let s = 0; s < this.constants.steps; s++) { + u = step(u); + } + return u; + }, { constants: { steps: STEPS } }); + const uRows = rows(u0, N); + return { shortcut: diffuse, run: () => diffuse(uRows) }; + }, + }; +} + +const MODES = [ + { label: 'plain JS', oracle: true }, + { label: 'webasm per-pass', perPass: true }, + { label: 'pipeline generic', kind: 'generic', hook: pipeline => (pipeline._fusionDisabled = true) }, + { label: 'pipeline fused-sync', kind: 'fused-sync', hook: pipeline => (pipeline._threadsDisabled = true) }, + { label: 'pipeline fused-threaded', kind: 'fused-threaded' }, +]; + +async function timeRuns(run) { + const times = []; + let runs = 5; + for (let i = 0; i < runs; i++) { + const start = process.hrtime.bigint(); + await run(); + const ms = Number(process.hrtime.bigint() - start) / 1e6; + times.push(ms); + if (ms > 2000) runs = Math.min(runs, i + 2); + } + times.sort((a, b) => a - b); + return +times[Math.floor(times.length / 2)].toFixed(2); +} + +async function main() { + const table = []; + for (const workload of [jacobi(), heat()]) { + const inputs = workload.make(); + const row = { name: workload.name, modes: {} }; + let expected = null; + for (const mode of MODES) { + let gpu = null; + let built; + if (mode.oracle) { + built = { run: async () => workload.js(inputs) }; + } else { + gpu = new GPU({ mode: 'webasm' }); + if (mode.perPass) { + built = await workload.perPass(gpu, inputs); + } else { + built = workload.buildPipeline(gpu, inputs); + if (mode.hook) mode.hook(built.shortcut.pipeline); + } + } + // correctness gate before any timing; also the compile/pool warmup + const checksum = workload.reduce(await built.run()); + if (mode.oracle) { + expected = checksum; + } else { + const err = relativeError(expected, checksum); + if (err > 1e-3) { + throw new Error(`CHECKSUM MISMATCH in ${ workload.name } (${ mode.label }): ${ checksum } vs ${ expected } (relative ${ err })`); + } + } + if (mode.kind && built.shortcut.executorKind !== mode.kind) { + throw new Error(`EXECUTOR MISMATCH in ${ workload.name } (${ mode.label }): got '${ built.shortcut.executorKind }' (fallbackReason: ${ built.shortcut.fallbackReason })`); + } + const ms = await timeRuns(built.run); + row.modes[mode.label] = { ms, checksum }; + process.stderr.write(`${ workload.name } / ${ mode.label }: ${ ms } ms (checksum ${ checksum.toFixed(6) })\n`); + if (gpu) await gpu.destroy(); + } + table.push(row); + } + + const labels = MODES.map(mode => mode.label); + console.log(`\n| Workload | ${ labels.join(' | ') } |`); + console.log(`|---|${ labels.map(() => '---').join('|') }|`); + for (const row of table) { + const baseline = row.modes['webasm per-pass'].ms; + console.log(`| ${ row.name } | ${ labels.map(label => { + const ms = row.modes[label].ms; + const speedup = label === 'webasm per-pass' ? ' (1×)' : ` (${ (baseline / ms).toFixed(2) }×)`; + return `${ ms } ms${ speedup }`; + }).join(' | ') } |`); + } + console.log('\n' + JSON.stringify(table, null, 2)); +} + +main().catch(error => { + console.error(error); + process.exit(1); +}); From 5034e452c790b9ae3d75b789aa10632e0b9df0ab Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 13:35:40 +0800 Subject: [PATCH 05/16] docs(pipeline): README section and index.d.ts declarations Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/index.d.ts | 20 ++++++++++++++++++-- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bb53f435..5d7d9987 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ Notice documentation is off? We do try our hardest, but if you find something, * [Dealing With Transpilation](#dealing-with-transpilation) * [WebGPU](#webgpu) * [WebAssembly](#webassembly) +* [Pipeline Compilation](#pipeline-compilation) * [Asynchronous Kernels](#asynchronous-kernels) * [Full API reference](#full-api-reference) * [How possible in node](#how-possible-in-node) @@ -1353,6 +1354,53 @@ A kernel is priced by the work it describes. A scatter algorithm rewritten gath `GPU.isWebAssemblySupported` reports the platform answer. `pipeline: true` is accepted the way the cpu backend accepts it: there is no device memory to pipeline into, so the result is a plain typed array (a fresh copy per call) that passes straight into downstream kernels. Not yet supported: graphical mode, kernel maps, and texture/image arguments all **degrade to the cpu backend** — in auto modes and under explicit `mode: 'webasm'` alike — the console warning names the reason and `kernel.kernel.fallbackReason` carries it queryably; a graphical fallback renders into the kernel's own canvas; `toString()` throws. Threaded runs accept a `poolSize` setting to cap the worker pool (defaults to `hardwareConcurrency`, or 4 when it cannot be read). `precision: 'unsigned'` is accepted and computed as single precision — wasm has no packed storage to be lossy in. +## Pipeline Compilation + +**New!** + +`gpu.createPipeline` compiles a whole multi-kernel computation — loops included — into one callable plan: + +```js +const sweep = gpu.createKernel(function(u, q) { + const x = this.thread.x, y = this.thread.y; + if (x === 0 || y === 0 || x === this.constants.hi || y === this.constants.hi) return u[y][x]; + return 0.25 * (u[y][x - 1] + u[y][x + 1] + u[y - 1][x] + u[y + 1][x] + q[y][x]); +}, { constants: { hi: 1023 }, output: [1024, 1024] }); + +const solve = gpu.createPipeline(function(u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; +}, { constants: { sweeps: 512 } }); + +const result = await solve(u0, q); // one launch, fences inside, one readback +``` + +The orchestration function runs **once**, at build time (the first call), with opaque handles standing in for its arguments. The kernel calls it makes are recorded — nothing executes — and plain JS control flow simply unrolls: the loop above records 512 steps over ONE kernel and two alternating buffers (a step that would overwrite data a later step still reads gets double-buffering automatically; liveness is static because the unrolled plan is a DAG). Every later call executes the compiled plan without re-entering your code, intermediates never leave device memory, and you pay one readback at the end. Return a handle, an Array of handles, or a plain object of handles — the call resolves to the same shape holding plain results. Not to be confused with [Pipelining](#pipelining): `pipeline: true` keeps one kernel's *output* resident and leaves the orchestration to you per call; `createPipeline` compiles the orchestration itself. Inner kernels do **not** need `pipeline: true` — intermediate residency is the pipeline's business, and kernels stay shared between pipelines and direct use. + +Because orchestration is tracing, not running, these are the rules — each violation throws at build, naming itself: + +* **A handle cannot be read.** Elements, properties, `.toArray()` — anything that would need the value throws `pipeline intermediate results cannot be read during orchestration`. A handle's only legal destinations are a kernel argument and the return value. +* **A handle cannot be used in arithmetic or a condition.** `if (u > 0)`, `u + 1`, `` `${u}` `` — anything that coerces throws. Loop bounds and branches must come from `this.constants`, pipeline settings, or plain captured values. +* **`Math.random()` throws during orchestration.** A trace-time draw would freeze one number into every later call; orchestration must be deterministic. `Math.random()` *inside kernels* is untouched — seeds are drawn per call, per step, at execution time. +* **Only kernel calls are recorded, and only kernels created by the same `GPU` instance.** Anything else a handle escapes into throws where detection is possible — handles are frozen, own-property-free class instances, so nearly any use trips a trap — but a function that merely stores a handle without touching it is beyond detection; what it stored is useless anyway. +* **Non-handle values freeze into the plan at trace time.** `this.constants` are trace-time facts (`sweeps: 512` above *is* the unroll count) — change them with `pipeline.setConstants({...})`, which invalidates the plan and re-traces on the next call, exactly the settings contract kernels already follow. Closure-captured values behave the same way: snapshotted when the trace reads them, like constants. Arguments passed to the *pipeline* are sampled at call time and uploaded once per call. + +Calling a pipeline **always returns a Promise** — the [async contract](#asynchronous-kernels) — and concurrent calls to one pipeline serialize in call order, like threaded kernels. `pipeline.destroy()` releases the plan's buffers and instances, and `gpu.destroy()` reaches pipelines the way it reaches kernels. + +Every backend runs pipelines. The reference path (`executorKind: 'generic'`) walks the plan through the normal kernel machinery — private per-pipeline kernel instances with `pipeline: true` forced on, your kernel's settings never observably touched — so on GL it is textures end-to-end. On **webasm** the plan *fuses*: every step compiles over one shared `WebAssembly.Memory` laid out `[pipeline args | plan buffers]`, passes run back-to-back with intermediates never copied out between steps (`'fused-sync'`), and where wasm threads are available the worker pool executes the *whole plan* per worker with Atomics-based barriers between steps — one dispatch per pipeline call, no main-thread round trip per pass (`'fused-threaded'`). Anything the webasm backend cannot take degrades to the generic executor under its usual contract: the reason is queryable at `pipeline.fallbackReason`, and `pipeline.executorKind` tells you which executor actually ran. + +What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): PLACEHOLDER-1× on heat threaded, PLACEHOLDER-2× on jacobi, against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. + +Not in v1, stated plainly: + +* **No mid-plan readback.** The plan runs start to finish; you cannot inspect an intermediate and stop early. The name `this.check` on the orchestration context is **reserved** for this: the future design records `this.check(handle, predicate)` as a checkpoint step where the executor reads back a small reduction every N passes and ends the plan early when the predicate answers converged — residual thresholds in iterative solvers, without surrendering the fused loop. Nothing you write today should put a `check` on the orchestration `this`. +* **No graphical kernels inside pipelines** — throws at build. +* **No kernel maps inside pipelines** — throws at build. +* **No webgpu command-encoder lowering** — webgpu runs pipelines through the generic executor (correct, one readback, but one submit per step); single-encoder lowering is future work. +* **`toString()` is deferred** — a pipeline cannot be exported as source yet. + ## Asynchronous Kernels **New in 2.20.0!** diff --git a/src/index.d.ts b/src/index.d.ts index 255f5b0a..52f2c719 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -399,9 +399,12 @@ export interface IKernelMapRunShortcut extends IKernelRunShortcut * Opaque stand-in for an intermediate result during pipeline orchestration. * Reading elements or properties, or using it in arithmetic or conditions, * throws at build time; its only legal uses are as a kernel argument and in - * the orchestration function's return value. + * the orchestration function's return value. Typed `any` because the same + * kernel shortcut that normally returns values returns handles while a trace + * is open — a distinction the type system cannot express; the trace enforces + * it at build time with named errors. */ -export interface IPipelineHandle {} +export type IPipelineHandle = any; export type PipelineFunction = (this: { constants: IConstantsThis }, ...args: IPipelineHandle[]) => IPipelineHandle | IPipelineHandle[] | { [key: string]: IPipelineHandle }; @@ -413,8 +416,21 @@ export interface IPipelineSettings { export type PipelineResult = KernelOutput | KernelOutput[] | { [key: string]: KernelOutput }; +/** the underlying Pipeline instance behind an IPipelineRunShortcut */ +export interface IPipeline { + constants: IConstants; + destroyed: boolean; + executorKind: string; + fallbackReason: string | null; + plan: object | null; + call(args: KernelVariable[] | IArguments): Promise; + setConstants(constants: IConstants): this; + destroy(): Promise; +} + export interface IPipelineRunShortcut { (...args: KernelVariable[]): Promise; + pipeline: IPipeline; setConstants(constants: IConstants): this; destroy(): Promise; /** From de07da36f737849706eca224b7cee3876aaf8613 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 14:26:54 +0800 Subject: [PATCH 06/16] fix(pipeline): the twelve findings of the build review, all reproduced first Tracer soundness: async/generator orchestration functions throw the named message instead of silently compiling an empty plan; handles gain ownKeys/has/getOwnPropertyDescriptor traps so object spread and key enumeration throw instead of reading empty; a handle cached across a re-trace (or leaked between pipelines) throws instead of yielding {}; empty result objects throw. Clone fidelity: plan clones inherit randomSeed, returnType, and the types the user PINNED (a new declaredArgumentTypes captured at kernel creation, distinct from build-inferred types), and the fused recompile re-applies them instead of nulling; extra type-signature programs clone from the plan's frozen clone, never the live user kernel, so a setOutput between trace and recompile cannot bake the wrong shape. Threaded barriers: generations are now MONOTONIC across the executor's life -- nothing is ever reset under a laggard worker, and no ack-wait precedes a dispatch (a silently terminated browser worker never acks; the interim await-acks fix deadlocked exactly there). Aborts retire every worker still owing acks -- the only place a silent browser death is detectable -- and the abort flag clears on the next run's dispatch. The stall backstop counts barrier arrivals as progress and defaults to 60s, so legitimately slow steps stop rejecting as wedged. Lifecycle: gpu.destroy() awaits pipeline teardown inside its promise (workers and shared memory are gone when it resolves); call-time texture arguments snapshot via clone() with the clones released on settlement -- which surfaced that clone() on a MUTABLE kernel's output was broken backend-wide (copy-on-write only ran under immutable); the render path now honors outstanding clone refs unconditionally. The recycling suite's mutable-leak test now spies newTexture (the leak signal) instead of beforeMutate (now the every-render refs check). Every fix verified against the review's own reproduction scripts. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 2 +- dist/gpu-browser-core.js | 121 ++++++++++++++---- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 121 ++++++++++++++---- dist/gpu-browser.min.js | 4 +- src/backend/kernel.js | 10 ++ src/backend/web-assembly/pipeline-executor.js | 56 ++++++-- src/backend/web-gl/kernel.js | 9 +- src/gpu.js | 59 +++++---- src/pipeline.js | 93 ++++++++++++-- test/features/pipeline/fused-webasm.js | 2 +- test/features/pipeline/threaded-webasm.js | 9 +- test/internal/recycling.js | 9 +- 13 files changed, 393 insertions(+), 106 deletions(-) diff --git a/README.md b/README.md index 5d7d9987..5bac628d 100644 --- a/README.md +++ b/README.md @@ -1391,7 +1391,7 @@ Calling a pipeline **always returns a Promise** — the [async contract](#asynch Every backend runs pipelines. The reference path (`executorKind: 'generic'`) walks the plan through the normal kernel machinery — private per-pipeline kernel instances with `pipeline: true` forced on, your kernel's settings never observably touched — so on GL it is textures end-to-end. On **webasm** the plan *fuses*: every step compiles over one shared `WebAssembly.Memory` laid out `[pipeline args | plan buffers]`, passes run back-to-back with intermediates never copied out between steps (`'fused-sync'`), and where wasm threads are available the worker pool executes the *whole plan* per worker with Atomics-based barriers between steps — one dispatch per pipeline call, no main-thread round trip per pass (`'fused-threaded'`). Anything the webasm backend cannot take degrades to the generic executor under its usual contract: the reason is queryable at `pipeline.fallbackReason`, and `pipeline.executorKind` tells you which executor actually ran. -What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): PLACEHOLDER-1× on heat threaded, PLACEHOLDER-2× on jacobi, against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. +What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): **3.3× on heat threaded, 5.3× on jacobi** (400 ms vs 2137 ms per-pass; heat 1321 ms vs 4310 ms), against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. Not in v1, stated plainly: diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 9d2bb2ea..8bb346c8 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -1077,6 +1077,7 @@ this.onRequestSwitchKernel = null; this.argumentNames = typeof source === "string" ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; + this.declaredArgumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; @@ -1122,6 +1123,11 @@ for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { + case "argumentTypes": + this.argumentTypes = settings[p]; + if (settings[p]) this.declaredArgumentTypes = Array.isArray(settings[p]) ? settings[p].slice() : settings[p]; + continue; + case "output": if (!Array.isArray(settings.output)) { this.setOutput(settings.output); @@ -1354,6 +1360,7 @@ return this; } setArgumentTypes(argumentTypes) { + this.declaredArgumentTypes = Array.isArray(argumentTypes) ? argumentTypes.slice() : argumentTypes; if (Array.isArray(argumentTypes)) this.argumentTypes = argumentTypes; else { this.argumentTypes = []; for (const p in argumentTypes) { @@ -9725,7 +9732,7 @@ return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); - if (this.immutable) this._replaceOutputTexture(); + this._replaceOutputTexture(); if (this.subKernels !== null) { if (this.immutable) this._replaceSubOutputTextures(); this.drawBuffers(); @@ -19162,7 +19169,7 @@ this.f32 = null; this.i32 = null; this.pool = null; - this.sanityTimeoutMs = 1e4; + this.sanityTimeoutMs = 6e4; this._entry = null; this._abortError = null; this._stepRuns = null; @@ -19191,7 +19198,7 @@ cloneClaimed[step.kernel] = true; kernel = kernelEntry.clone.kernel; } else { - const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + const extra = this.pipeline._cloneKernel(kernelEntry.clone); this._extraShortcuts.push(extra); kernel = extra.kernel; } @@ -19519,7 +19526,7 @@ return reps; } _prepareKernel(kernel, reps) { - kernel.argumentTypes = null; + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; kernel.setupConstants(); kernel.setupArguments(reps); for (let i = 0; i < kernel.argumentTypes.length; i++) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.argumentTypes[i]) === -1) throw new FusionFallback(`argument "${kernel.argumentNames[i]}" of type ${kernel.argumentTypes[i]} is not supported on the webasm backend`); @@ -19566,12 +19573,17 @@ _executeThreaded(args) { const entry = this._entry; const i32 = this.i32; - Atomics.store(i32, entry.genIndex, 0); - Atomics.store(i32, entry.countIndex, 0); const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); - const finalGen = this._stepRuns.length; + if (this._lastRunAborted) { + Atomics.store(i32, entry.countIndex, 0); + Atomics.store(i32, entry.abortIndex, 0); + this._lastRunAborted = false; + this._abortError = null; + } + const baseGen = Atomics.load(i32, entry.genIndex); + const finalGen = baseGen + this._stepRuns.length; this.pool.dispatchPipeline(entry, { - baseGen: 0, + baseGen: baseGen, seeds: seeds }).then(null, error => this._abort(error)); return this._waitForGeneration(finalGen).then(() => this._readResults(args)); @@ -19586,7 +19598,9 @@ if (keepAlive !== null) clearInterval(keepAlive); fn(value); }; + const countIndex = this._entry.countIndex; let lastSeen = Atomics.load(i32, genIndex); + let lastCount = Atomics.load(i32, countIndex); let lastProgress = Date.now(); const check = () => { if (this._abortError) { @@ -19598,8 +19612,10 @@ settle(resolve); return; } - if (gen !== lastSeen) { + const count = Atomics.load(i32, countIndex); + if (gen !== lastSeen || count !== lastCount) { lastSeen = gen; + lastCount = count; lastProgress = Date.now(); } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { const error = new Error(`pipeline threaded barrier stalled at generation ${gen} of ${target} for ${this.sanityTimeoutMs}ms`); @@ -19619,10 +19635,14 @@ _abort(error) { if (this._abortError) return; this._abortError = error || new Error("pipeline threaded run aborted"); + this._lastRunAborted = true; if (this.i32 && this._entry) { Atomics.store(this.i32, this._entry.abortIndex, 1); Atomics.notify(this.i32, this._entry.genIndex); } + if (this.pool && this.pool.workers) { + for (const worker of this.pool.workers) if (!worker.dead && worker.state.pending.size > 0) worker.die(this._abortError); + } } abortRuns(error) { if (this.threaded) this._abort(error); @@ -19682,6 +19702,8 @@ const MSG_RETURN_SHAPE = "a pipeline must return a handle, or an Array or plain object of handles"; const MSG_FIXED_OUTPUT = "kernels called inside a pipeline must have a fixed output size"; const MSG_DESTROYED = "pipeline has been destroyed"; + const MSG_ASYNC_ORCHESTRATION = "the orchestration function must be synchronous; async functions and generators cannot be traced"; + const MSG_STALE_HANDLE = "this handle belongs to a different trace; handles do not survive re-trace or cross pipelines"; var PipelineHandle = class {}; let activeTrace = null; function getActiveTrace() { @@ -19694,6 +19716,7 @@ this.kernels = []; this.kernelIndexes = new Map; this.handleMeta = new WeakMap; + this.held = []; } createHandle(meta) { const trace = this; @@ -19707,6 +19730,15 @@ }, set() { throw new Error(MSG_HANDLE_READ); + }, + ownKeys() { + throw new Error(MSG_HANDLE_READ); + }, + has() { + throw new Error(MSG_HANDLE_READ); + }, + getOwnPropertyDescriptor() { + throw new Error(MSG_HANDLE_READ); } }); trace.handleMeta.set(handle, meta); @@ -19741,20 +19773,34 @@ bindValue(value) { const meta = this.handleMeta.get(value); if (meta) return meta; + if (value instanceof PipelineHandle) throw new Error(MSG_STALE_HANDLE); return { source: "literal", - value: snapshotValue(value) + value: snapshotValue(value, this.held) }; } }; - function snapshotValue(value) { + function snapshotValue(value, held) { if (!value || typeof value !== "object") return value; - if (typeof value.delete === "function" || typeof value.toArray === "function") return value; + if (typeof value.delete === "function" || typeof value.toArray === "function") { + if (typeof value.clone === "function" && held) { + const cloned = value.clone(); + held.push(cloned); + return cloned; + } + return value; + } if (ArrayBuffer.isView(value)) return value.slice(0); - if (Array.isArray(value)) return value.map(snapshotValue); - if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } + function releaseSnapshots(held) { + for (let i = 0; i < held.length; i++) try { + held[i].delete(); + } catch (e) {} + held.length = 0; + } function assignBuffers(steps, resultBindings) { const lastRead = new Array(steps.length).fill(-1); for (let i = 0; i < steps.length; i++) { @@ -19809,7 +19855,11 @@ binding: trace.bindValue(value) })) }; + if (returned instanceof PipelineHandle) throw new Error(MSG_STALE_HANDLE); if (typeof returned === "object" && !ArrayBuffer.isView(returned)) { + if (typeof returned.then === "function") throw new Error(MSG_ASYNC_ORCHESTRATION); + const proto = Object.getPrototypeOf(returned); + if (proto !== Object.prototype && proto !== null) throw new Error(MSG_RETURN_SHAPE); const entries = []; for (const key in returned) { if (!returned.hasOwnProperty(key)) continue; @@ -19818,6 +19868,7 @@ binding: trace.bindValue(returned[key]) }); } + if (entries.length === 0) throw new Error(MSG_RETURN_SHAPE); return { kind: "object", entries: entries @@ -19844,7 +19895,8 @@ call(args) { if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); - for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); + const held = []; + for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); const promise = this._tail.then(() => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { @@ -19870,6 +19922,7 @@ } return this._executeGeneric(this.plan, sampled); }); + if (held.length > 0) promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); this._tail = promise.then(noop, noop); return promise; } @@ -19916,6 +19969,8 @@ activeTrace = trace; let returned; try { + const ctorName = this.fn.constructor && this.fn.constructor.name; + if (ctorName === "AsyncFunction" || ctorName === "GeneratorFunction" || ctorName === "AsyncGeneratorFunction") throw new Error(MSG_ASYNC_ORCHESTRATION); returned = this.fn.apply({ constants: Object.assign({}, this.constants) }, argHandles); @@ -19933,7 +19988,8 @@ steps: trace.steps, buffers: buffers, results: results, - kernels: kernels + kernels: kernels, + held: trace.held }; } _prepareExecutor(args) { @@ -19967,7 +20023,8 @@ immutable: true, dynamicArguments: true }; - const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug" ]; + const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug", "randomSeed", "returnType" ]; + if (kernel.declaredArgumentTypes) settings.argumentTypes = kernel.declaredArgumentTypes.slice(); for (let i = 0; i < optional.length; i++) { const name = optional[i]; if (kernel[name] !== null && kernel[name] !== void 0) settings[name] = kernel[name]; @@ -20023,6 +20080,7 @@ const clone = kernels[i].clone; if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); } + if (this.plan.held) releaseSnapshots(this.plan.held); this.plan = null; } }; @@ -20616,21 +20674,30 @@ if (!this.kernels) resolve(); setTimeout(() => { try { + let pipelinesDone = Promise.resolve(); if (this.pipelines) { const pipelines = this.pipelines.slice(); - for (let i = 0; i < pipelines.length; i++) pipelines[i].destroy(); - } - const kernels = this.kernels.slice(); - for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); - let firstKernel = kernels[0]; - if (firstKernel) { - if (firstKernel.kernel) firstKernel = firstKernel.kernel; - if (firstKernel.constructor.destroyContext) firstKernel.constructor.destroyContext(this.context); + pipelinesDone = Promise.all(pipelines.map(pipeline => Promise.resolve(pipeline.destroy()).catch(() => void 0))); } + const destroyKernels = () => { + try { + const kernels = this.kernels.slice(); + for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); + let firstKernel = kernels[0]; + if (firstKernel) { + if (firstKernel.kernel) firstKernel = firstKernel.kernel; + if (firstKernel.constructor.destroyContext) firstKernel.constructor.destroyContext(this.context); + } + } catch (e) { + reject(e); + return; + } + resolve(); + }; + pipelinesDone.then(destroyKernels).catch(reject); } catch (e) { reject(e); } - resolve(); }, 0); }); } diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index cd0634f9..52a88c3c 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,r)=>{B.assignArgumentType(e,t,r)},L=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),C=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:_,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=I.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:E},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),I.set(o,l)}_[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:_.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=_,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32;Atomics.store(r,t.genIndex,0),Atomics.store(r,t.countIndex,0);const n=this._stepRuns.map(e=>this._drawSeed(e)),s=this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:0,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(s).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)};let u=Atomics.load(t,r),l=Date.now();const h=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)o(s);else{if(a!==u)u=a,l=Date.now();else if(Date.now()-l>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(h):Promise.resolve().then(h)}else setTimeout(h,1)}};h()})}_abort(e){this._abortError||(this._abortError=e||new Error("pipeline threaded run aborted"),this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)))}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=r.then(d,d),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const r=[];for(const n in t)t.hasOwnProperty(n)&&r.push({key:n,binding:e.bindValue(t[n])});return{kind:"object",entries:r}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,r)=>{B.assignArgumentType(e,t,r)},L=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:k,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=I.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:E},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),I.set(o,l)}_[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:_.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=_,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e instanceof r?new r(p(e.value,t),e.size):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index afebe81d..b09b05ed 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -5271,6 +5271,7 @@ this.onRequestSwitchKernel = null; this.argumentNames = typeof source === "string" ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; + this.declaredArgumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; @@ -5316,6 +5317,11 @@ for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { + case "argumentTypes": + this.argumentTypes = settings[p]; + if (settings[p]) this.declaredArgumentTypes = Array.isArray(settings[p]) ? settings[p].slice() : settings[p]; + continue; + case "output": if (!Array.isArray(settings.output)) { this.setOutput(settings.output); @@ -5548,6 +5554,7 @@ return this; } setArgumentTypes(argumentTypes) { + this.declaredArgumentTypes = Array.isArray(argumentTypes) ? argumentTypes.slice() : argumentTypes; if (Array.isArray(argumentTypes)) this.argumentTypes = argumentTypes; else { this.argumentTypes = []; for (const p in argumentTypes) { @@ -13922,7 +13929,7 @@ return; } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); - if (this.immutable) this._replaceOutputTexture(); + this._replaceOutputTexture(); if (this.subKernels !== null) { if (this.immutable) this._replaceSubOutputTextures(); this.drawBuffers(); @@ -23359,7 +23366,7 @@ this.f32 = null; this.i32 = null; this.pool = null; - this.sanityTimeoutMs = 1e4; + this.sanityTimeoutMs = 6e4; this._entry = null; this._abortError = null; this._stepRuns = null; @@ -23388,7 +23395,7 @@ cloneClaimed[step.kernel] = true; kernel = kernelEntry.clone.kernel; } else { - const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + const extra = this.pipeline._cloneKernel(kernelEntry.clone); this._extraShortcuts.push(extra); kernel = extra.kernel; } @@ -23716,7 +23723,7 @@ return reps; } _prepareKernel(kernel, reps) { - kernel.argumentTypes = null; + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; kernel.setupConstants(); kernel.setupArguments(reps); for (let i = 0; i < kernel.argumentTypes.length; i++) if (SUPPORTED_VALUE_TYPES.indexOf(kernel.argumentTypes[i]) === -1) throw new FusionFallback(`argument "${kernel.argumentNames[i]}" of type ${kernel.argumentTypes[i]} is not supported on the webasm backend`); @@ -23763,12 +23770,17 @@ _executeThreaded(args) { const entry = this._entry; const i32 = this.i32; - Atomics.store(i32, entry.genIndex, 0); - Atomics.store(i32, entry.countIndex, 0); const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); - const finalGen = this._stepRuns.length; + if (this._lastRunAborted) { + Atomics.store(i32, entry.countIndex, 0); + Atomics.store(i32, entry.abortIndex, 0); + this._lastRunAborted = false; + this._abortError = null; + } + const baseGen = Atomics.load(i32, entry.genIndex); + const finalGen = baseGen + this._stepRuns.length; this.pool.dispatchPipeline(entry, { - baseGen: 0, + baseGen: baseGen, seeds: seeds }).then(null, error => this._abort(error)); return this._waitForGeneration(finalGen).then(() => this._readResults(args)); @@ -23783,7 +23795,9 @@ if (keepAlive !== null) clearInterval(keepAlive); fn(value); }; + const countIndex = this._entry.countIndex; let lastSeen = Atomics.load(i32, genIndex); + let lastCount = Atomics.load(i32, countIndex); let lastProgress = Date.now(); const check = () => { if (this._abortError) { @@ -23795,8 +23809,10 @@ settle(resolve); return; } - if (gen !== lastSeen) { + const count = Atomics.load(i32, countIndex); + if (gen !== lastSeen || count !== lastCount) { lastSeen = gen; + lastCount = count; lastProgress = Date.now(); } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { const error = new Error(`pipeline threaded barrier stalled at generation ${gen} of ${target} for ${this.sanityTimeoutMs}ms`); @@ -23816,10 +23832,14 @@ _abort(error) { if (this._abortError) return; this._abortError = error || new Error("pipeline threaded run aborted"); + this._lastRunAborted = true; if (this.i32 && this._entry) { Atomics.store(this.i32, this._entry.abortIndex, 1); Atomics.notify(this.i32, this._entry.genIndex); } + if (this.pool && this.pool.workers) { + for (const worker of this.pool.workers) if (!worker.dead && worker.state.pending.size > 0) worker.die(this._abortError); + } } abortRuns(error) { if (this.threaded) this._abort(error); @@ -23879,6 +23899,8 @@ const MSG_RETURN_SHAPE = "a pipeline must return a handle, or an Array or plain object of handles"; const MSG_FIXED_OUTPUT = "kernels called inside a pipeline must have a fixed output size"; const MSG_DESTROYED = "pipeline has been destroyed"; + const MSG_ASYNC_ORCHESTRATION = "the orchestration function must be synchronous; async functions and generators cannot be traced"; + const MSG_STALE_HANDLE = "this handle belongs to a different trace; handles do not survive re-trace or cross pipelines"; var PipelineHandle = class {}; let activeTrace = null; function getActiveTrace() { @@ -23891,6 +23913,7 @@ this.kernels = []; this.kernelIndexes = new Map; this.handleMeta = new WeakMap; + this.held = []; } createHandle(meta) { const trace = this; @@ -23904,6 +23927,15 @@ }, set() { throw new Error(MSG_HANDLE_READ); + }, + ownKeys() { + throw new Error(MSG_HANDLE_READ); + }, + has() { + throw new Error(MSG_HANDLE_READ); + }, + getOwnPropertyDescriptor() { + throw new Error(MSG_HANDLE_READ); } }); trace.handleMeta.set(handle, meta); @@ -23938,20 +23970,34 @@ bindValue(value) { const meta = this.handleMeta.get(value); if (meta) return meta; + if (value instanceof PipelineHandle) throw new Error(MSG_STALE_HANDLE); return { source: "literal", - value: snapshotValue(value) + value: snapshotValue(value, this.held) }; } }; - function snapshotValue(value) { + function snapshotValue(value, held) { if (!value || typeof value !== "object") return value; - if (typeof value.delete === "function" || typeof value.toArray === "function") return value; + if (typeof value.delete === "function" || typeof value.toArray === "function") { + if (typeof value.clone === "function" && held) { + const cloned = value.clone(); + held.push(cloned); + return cloned; + } + return value; + } if (ArrayBuffer.isView(value)) return value.slice(0); - if (Array.isArray(value)) return value.map(snapshotValue); - if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } + function releaseSnapshots(held) { + for (let i = 0; i < held.length; i++) try { + held[i].delete(); + } catch (e) {} + held.length = 0; + } function assignBuffers(steps, resultBindings) { const lastRead = new Array(steps.length).fill(-1); for (let i = 0; i < steps.length; i++) { @@ -24006,7 +24052,11 @@ binding: trace.bindValue(value) })) }; + if (returned instanceof PipelineHandle) throw new Error(MSG_STALE_HANDLE); if (typeof returned === "object" && !ArrayBuffer.isView(returned)) { + if (typeof returned.then === "function") throw new Error(MSG_ASYNC_ORCHESTRATION); + const proto = Object.getPrototypeOf(returned); + if (proto !== Object.prototype && proto !== null) throw new Error(MSG_RETURN_SHAPE); const entries = []; for (const key in returned) { if (!returned.hasOwnProperty(key)) continue; @@ -24015,6 +24065,7 @@ binding: trace.bindValue(returned[key]) }); } + if (entries.length === 0) throw new Error(MSG_RETURN_SHAPE); return { kind: "object", entries: entries @@ -24041,7 +24092,8 @@ call(args) { if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); - for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i]); + const held = []; + for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); const promise = this._tail.then(() => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { @@ -24067,6 +24119,7 @@ } return this._executeGeneric(this.plan, sampled); }); + if (held.length > 0) promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); this._tail = promise.then(noop, noop); return promise; } @@ -24113,6 +24166,8 @@ activeTrace = trace; let returned; try { + const ctorName = this.fn.constructor && this.fn.constructor.name; + if (ctorName === "AsyncFunction" || ctorName === "GeneratorFunction" || ctorName === "AsyncGeneratorFunction") throw new Error(MSG_ASYNC_ORCHESTRATION); returned = this.fn.apply({ constants: Object.assign({}, this.constants) }, argHandles); @@ -24130,7 +24185,8 @@ steps: trace.steps, buffers: buffers, results: results, - kernels: kernels + kernels: kernels, + held: trace.held }; } _prepareExecutor(args) { @@ -24164,7 +24220,8 @@ immutable: true, dynamicArguments: true }; - const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug" ]; + const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug", "randomSeed", "returnType" ]; + if (kernel.declaredArgumentTypes) settings.argumentTypes = kernel.declaredArgumentTypes.slice(); for (let i = 0; i < optional.length; i++) { const name = optional[i]; if (kernel[name] !== null && kernel[name] !== void 0) settings[name] = kernel[name]; @@ -24220,6 +24277,7 @@ const clone = kernels[i].clone; if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); } + if (this.plan.held) releaseSnapshots(this.plan.held); this.plan = null; } }; @@ -24813,21 +24871,30 @@ if (!this.kernels) resolve(); setTimeout(() => { try { + let pipelinesDone = Promise.resolve(); if (this.pipelines) { const pipelines = this.pipelines.slice(); - for (let i = 0; i < pipelines.length; i++) pipelines[i].destroy(); - } - const kernels = this.kernels.slice(); - for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); - let firstKernel = kernels[0]; - if (firstKernel) { - if (firstKernel.kernel) firstKernel = firstKernel.kernel; - if (firstKernel.constructor.destroyContext) firstKernel.constructor.destroyContext(this.context); + pipelinesDone = Promise.all(pipelines.map(pipeline => Promise.resolve(pipeline.destroy()).catch(() => void 0))); } + const destroyKernels = () => { + try { + const kernels = this.kernels.slice(); + for (let i = 0; i < kernels.length; i++) kernels[i].destroy(true); + let firstKernel = kernels[0]; + if (firstKernel) { + if (firstKernel.kernel) firstKernel = firstKernel.kernel; + if (firstKernel.constructor.destroyContext) firstKernel.constructor.destroyContext(this.context); + } + } catch (e) { + reject(e); + return; + } + resolve(); + }; + pipelinesDone.then(destroyKernels).catch(reject); } catch (e) { reject(e); } - resolve(); }, 0); }); } diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index a0b7af11..11b1f599 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 13:28:18 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.shortcut);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32;Atomics.store(s,t.genIndex,0),Atomics.store(s,t.countIndex,0);const r=this._stepRuns.map(e=>this._drawSeed(e)),n=this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:0,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(n).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)};let u=Atomics.load(t,s),l=Date.now();const h=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)o(n);else{if(a!==u)u=a,l=Date.now();else if(Date.now()-l>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(h):Promise.resolve().then(h)}else setTimeout(h,1)}};h()})}_abort(e){this._abortError||(this._abortError=e||new Error("pipeline threaded run aborted"),this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)))}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed";var o=class{};let u=null;var l=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap}createHandle(e){const t=Object.freeze(new o),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;e{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return this._tail=s.then(d,d),s}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new l(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if("object"==typeof t&&!ArrayBuffer.isView(t)){const s=[];for(const r in t)t.hasOwnProperty(r)&&s.push({key:r,binding:e.bindValue(t[r])});return{kind:"object",entries:s}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),o=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:o}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug"];for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{if(this.pipelines){const e=this.pipelines.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e instanceof s?new s(p(e.value,t),e.size):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/backend/kernel.js b/src/backend/kernel.js index 340040b5..39db6dcd 100644 --- a/src/backend/kernel.js +++ b/src/backend/kernel.js @@ -75,6 +75,9 @@ class Kernel { */ this.argumentNames = typeof source === 'string' ? utils.getArgumentNamesFromString(source) : null; this.argumentTypes = null; + // types the user pinned at creation (vs types a build inferred): what a + // pipeline clone must inherit to compute exactly like the original + this.declaredArgumentTypes = null; this.argumentSizes = null; this.argumentBitRatios = null; this.kernelArguments = null; @@ -264,6 +267,12 @@ class Kernel { for (let p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; switch (p) { + case 'argumentTypes': + this.argumentTypes = settings[p]; + if (settings[p]) { + this.declaredArgumentTypes = Array.isArray(settings[p]) ? settings[p].slice() : settings[p]; + } + continue; case 'output': if (!Array.isArray(settings.output)) { this.setOutput(settings.output); // Flatten output object @@ -760,6 +769,7 @@ class Kernel { * @return {this} */ setArgumentTypes(argumentTypes) { + this.declaredArgumentTypes = Array.isArray(argumentTypes) ? argumentTypes.slice() : argumentTypes; if (Array.isArray(argumentTypes)) { this.argumentTypes = argumentTypes; } else { diff --git a/src/backend/web-assembly/pipeline-executor.js b/src/backend/web-assembly/pipeline-executor.js index c319d7e4..27b7a260 100644 --- a/src/backend/web-assembly/pipeline-executor.js +++ b/src/backend/web-assembly/pipeline-executor.js @@ -106,7 +106,7 @@ class WebAssemblyPipelineExecutor { // a stalled barrier is a hang without this: reject when the generation // counter makes no progress for this long (per step, not per run, so // arbitrarily long plans stay legal as long as steps keep landing) - this.sanityTimeoutMs = 10000; + this.sanityTimeoutMs = 60000; this._entry = null; this._abortError = null; this._stepRuns = null; @@ -147,7 +147,10 @@ class WebAssemblyPipelineExecutor { cloneClaimed[step.kernel] = true; kernel = kernelEntry.clone.kernel; } else { - const extra = this.pipeline._cloneKernel(kernelEntry.shortcut); + // from the plan's frozen clone, NOT the live user kernel: a + // setOutput between trace and recompile must not bake the user's + // current shape over the plan's trace-time one + const extra = this.pipeline._cloneKernel(kernelEntry.clone); this._extraShortcuts.push(extra); kernel = extra.kernel; } @@ -463,7 +466,9 @@ class WebAssemblyPipelineExecutor { * new signature, not keep the old one. */ _prepareKernel(kernel, reps) { - kernel.argumentTypes = null; + // re-infer for this signature -- except types the user pinned, which + // must type identically to a direct kernel call + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; kernel.setupConstants(); kernel.setupArguments(reps); for (let i = 0; i < kernel.argumentTypes.length; i++) { @@ -576,17 +581,33 @@ class WebAssemblyPipelineExecutor { _executeThreaded(args) { const entry = this._entry; const i32 = this.i32; - Atomics.store(i32, entry.genIndex, 0); - Atomics.store(i32, entry.countIndex, 0); const seeds = this._stepRuns.map(stepRun => this._drawSeed(stepRun)); - const finalGen = this._stepRuns.length; - const dispatched = this.pool.dispatchPipeline(entry, { baseGen: 0, seeds }); + // generations are MONOTONIC across the executor's life: each run's + // targets start from wherever the counter already is, so a laggard from + // the previous run that is still waking at its final barrier sees the + // counter at or past its own target and exits -- nothing is ever reset + // under it, and no ack-wait is needed before dispatching (a silently + // terminated browser worker never acks, so waiting on acks can hang + // forever). An i32 outlasts 5M runs of a 400-step plan before wrapping. + if (this._lastRunAborted) { + // an aborted run retired every worker still owing work, so no live + // laggard can touch the control words: clear the partial barrier + // fill and the abort flag for the respawned pool + Atomics.store(i32, entry.countIndex, 0); + Atomics.store(i32, entry.abortIndex, 0); + this._lastRunAborted = false; + this._abortError = null; + } + const baseGen = Atomics.load(i32, entry.genIndex); + const finalGen = baseGen + this._stepRuns.length; + const dispatched = this.pool.dispatchPipeline(entry, { baseGen, seeds }); // a dead worker rejects its task here; without the abort the surviving // workers would sit on a barrier that can never fill dispatched.then(null, error => this._abort(error)); return this._waitForGeneration(finalGen).then(() => this._readResults(args)); } + /** * Resolves when the generation counter reaches `target`, rejects on abort * or when the counter stalls past sanityTimeoutMs. Atomics.waitAsync @@ -607,7 +628,9 @@ class WebAssemblyPipelineExecutor { if (keepAlive !== null) clearInterval(keepAlive); fn(value); }; + const countIndex = this._entry.countIndex; let lastSeen = Atomics.load(i32, genIndex); + let lastCount = Atomics.load(i32, countIndex); let lastProgress = Date.now(); const check = () => { if (this._abortError) { @@ -619,8 +642,13 @@ class WebAssemblyPipelineExecutor { settle(resolve); return; } - if (gen !== lastSeen) { + // arrivals at the barrier are progress too -- a step whose slowest + // worker outlasts the backstop is slow, not wedged, as long as its + // peers keep arriving; a true deadlock moves neither counter + const count = Atomics.load(i32, countIndex); + if (gen !== lastSeen || count !== lastCount) { lastSeen = gen; + lastCount = count; lastProgress = Date.now(); } else if (Date.now() - lastProgress >= this.sanityTimeoutMs) { const error = new Error( @@ -656,10 +684,22 @@ class WebAssemblyPipelineExecutor { _abort(error) { if (this._abortError) return; this._abortError = error || new Error('pipeline threaded run aborted'); + this._lastRunAborted = true; if (this.i32 && this._entry) { Atomics.store(this.i32, this._entry.abortIndex, 1); Atomics.notify(this.i32, this._entry.genIndex); } + // whichever workers still owe acks are why the barrier stalled; retire + // them so the next run respawns fresh slots. A browser worker killed by + // terminate() dies SILENTLY (no error event) -- this is the only place + // that death is ever detected. + if (this.pool && this.pool.workers) { + for (const worker of this.pool.workers) { + if (!worker.dead && worker.state.pending.size > 0) { + worker.die(this._abortError); + } + } + } } /** diff --git a/src/backend/web-gl/kernel.js b/src/backend/web-gl/kernel.js index 96b79a16..ba96f132 100644 --- a/src/backend/web-gl/kernel.js +++ b/src/backend/web-gl/kernel.js @@ -698,9 +698,12 @@ class WebGLKernel extends GLKernel { } gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); - if (this.immutable) { - this._replaceOutputTexture(); - } + // not only for immutable kernels: clone() shares the underlying GL + // texture and counts a ref, so a mutable kernel re-rendering must honor + // outstanding clones by detaching first (beforeMutate is a no-op when + // nothing was cloned) -- otherwise every clone silently reads the next + // run's values + this._replaceOutputTexture(); if (this.subKernels !== null) { if (this.immutable) { diff --git a/src/gpu.js b/src/gpu.js index d472f1d4..b9ccb8da 100644 --- a/src/gpu.js +++ b/src/gpu.js @@ -826,36 +826,49 @@ class GPU { try { // pipelines release their cloned kernel instances, which splice // themselves out of this.kernels -- so pipelines go first, then - // the surviving kernels + // the surviving kernels. Their releases queue behind in-flight + // call tails, so the whole teardown AWAITS them: gpu.destroy() + // resolving while a threaded executor's workers are still alive + // is a lie the caller acts on + let pipelinesDone = Promise.resolve(); if (this.pipelines) { const pipelines = this.pipelines.slice(); - for (let i = 0; i < pipelines.length; i++) { - pipelines[i].destroy(); - } - } - // kernel.destroy() splices itself out of this.kernels, so walk a copy: - // mutating the list being indexed skipped every other kernel, and left - // this.kernels[0] undefined below, which meant a single-kernel GPU - // never released its WebGL context at all - const kernels = this.kernels.slice(); - for (let i = 0; i < kernels.length; i++) { - kernels[i].destroy(true); // remove canvas if exists + pipelinesDone = Promise.all(pipelines.map(pipeline => Promise.resolve(pipeline.destroy()).catch(() => undefined))); } - // all kernels are associated with one context, go ahead and take care of it here - let firstKernel = kernels[0]; - if (firstKernel) { - // if it is shortcut - if (firstKernel.kernel) { - firstKernel = firstKernel.kernel; - } - if (firstKernel.constructor.destroyContext) { - firstKernel.constructor.destroyContext(this.context); + // a closure, not a method: destroy() is exercised against bare + // mock objects via GPU.prototype.destroy.call in the test suite, + // so `this` cannot be assumed to carry anything beyond data + const destroyKernels = () => { + try { + // kernel.destroy() splices itself out of this.kernels, so walk a copy: + // mutating the list being indexed skipped every other kernel, and left + // this.kernels[0] undefined below, which meant a single-kernel GPU + // never released its WebGL context at all + const kernels = this.kernels.slice(); + for (let i = 0; i < kernels.length; i++) { + kernels[i].destroy(true); // remove canvas if exists + } + // all kernels are associated with one context, go ahead and take care of it here + let firstKernel = kernels[0]; + if (firstKernel) { + // if it is shortcut + if (firstKernel.kernel) { + firstKernel = firstKernel.kernel; + } + if (firstKernel.constructor.destroyContext) { + firstKernel.constructor.destroyContext(this.context); + } + } + } catch (e) { + reject(e); + return; } - } + resolve(); + }; + pipelinesDone.then(destroyKernels).catch(reject); } catch (e) { reject(e); } - resolve(); }, 0); }); } diff --git a/src/pipeline.js b/src/pipeline.js index cee46463..39878e21 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -19,6 +19,8 @@ const MSG_KERNEL_MAP = 'kernel maps are not supported inside pipelines'; const MSG_RETURN_SHAPE = 'a pipeline must return a handle, or an Array or plain object of handles'; const MSG_FIXED_OUTPUT = 'kernels called inside a pipeline must have a fixed output size'; const MSG_DESTROYED = 'pipeline has been destroyed'; +const MSG_ASYNC_ORCHESTRATION = 'the orchestration function must be synchronous; async functions and generators cannot be traced'; +const MSG_STALE_HANDLE = 'this handle belongs to a different trace; handles do not survive re-trace or cross pipelines'; /** * The class exists for instanceof and for its name in errors; all state @@ -53,6 +55,8 @@ class PipelineTrace { this.kernels = []; this.kernelIndexes = new Map(); this.handleMeta = new WeakMap(); + // texture snapshots cloned during this trace; released with the plan + this.held = []; } /** @@ -76,6 +80,17 @@ class PipelineTrace { set() { throw new Error(MSG_HANDLE_READ); }, + // object spread and key enumeration consult these traps and never the + // get trap; without them `{ ...handle }` silently reads as empty + ownKeys() { + throw new Error(MSG_HANDLE_READ); + }, + has() { + throw new Error(MSG_HANDLE_READ); + }, + getOwnPropertyDescriptor() { + throw new Error(MSG_HANDLE_READ); + }, }); trace.handleMeta.set(handle, meta); return handle; @@ -130,7 +145,13 @@ class PipelineTrace { bindValue(value) { const meta = this.handleMeta.get(value); if (meta) return meta; - return { source: 'literal', value: snapshotValue(value) }; + // instanceof resolves through the untrapped getPrototypeOf, so a handle + // from a previous trace (or another pipeline) is detected without + // tripping its own traps + if (value instanceof PipelineHandle) { + throw new Error(MSG_STALE_HANDLE); + } + return { source: 'literal', value: snapshotValue(value, this.held) }; } } @@ -140,16 +161,35 @@ class PipelineTrace { * held at the call. Handles never reach this function -- bindValue checks * the WeakMap first -- so property access here cannot trip a handle trap. */ -function snapshotValue(value) { +function snapshotValue(value, held) { if (!value || typeof value !== 'object') return value; - // GPU-resident values cannot be mutated from JS between now and the run - if (typeof value.delete === 'function' || typeof value.toArray === 'function') return value; + if (typeof value.delete === 'function' || typeof value.toArray === 'function') { + // a mutable (immutable: false) texture is re-rendered IN PLACE by its + // kernel's next call, so passing it through uncopied would sample the + // contents at execution, not at the call; clone now and release the + // clone once the holder is done with it + if (typeof value.clone === 'function' && held) { + const cloned = value.clone(); + held.push(cloned); + return cloned; + } + return value; + } if (ArrayBuffer.isView(value)) return value.slice(0); - if (Array.isArray(value)) return value.map(snapshotValue); - if (value instanceof Input) return new Input(snapshotValue(value.value), value.size); + if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } +function releaseSnapshots(held) { + for (let i = 0; i < held.length; i++) { + try { + held[i].delete(); + } catch (e) {} + } + held.length = 0; +} + /** * Static liveness over the unrolled DAG, then greedy slot reuse: a step may * write a buffer only when the previous occupant's last reader ran strictly @@ -227,12 +267,30 @@ function bindResults(trace, returned) { entries: returned.map((value, i) => ({ key: i, binding: trace.bindValue(value) })), }; } + if (returned instanceof PipelineHandle) { + // a handle the current trace does not know: cached from a previous + // trace or leaked from another pipeline + throw new Error(MSG_STALE_HANDLE); + } if (typeof returned === 'object' && !ArrayBuffer.isView(returned)) { + if (typeof returned.then === 'function') { + throw new Error(MSG_ASYNC_ORCHESTRATION); + } + const proto = Object.getPrototypeOf(returned); + if (proto !== Object.prototype && proto !== null) { + // generator objects, class instances: not a plain bag of handles + throw new Error(MSG_RETURN_SHAPE); + } const entries = []; for (const key in returned) { if (!returned.hasOwnProperty(key)) continue; entries.push({ key, binding: trace.bindValue(returned[key]) }); } + if (entries.length === 0) { + // `{ ...handle }` and friends arrive here as an empty object; an + // empty result set is never what the caller meant + throw new Error(MSG_RETURN_SHAPE); + } return { kind: 'object', entries }; } throw new Error(MSG_RETURN_SHAPE); @@ -292,8 +350,9 @@ class Pipeline { call(args) { if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); + const held = []; for (let i = 0; i < args.length; i++) { - sampled[i] = snapshotValue(args[i]); + sampled[i] = snapshotValue(args[i], held); } const promise = this._tail.then(() => { if (this.destroyed) throw new Error(MSG_DESTROYED); @@ -330,6 +389,10 @@ class Pipeline { } return this._executeGeneric(this.plan, sampled); }); + if (held.length > 0) { + // cloned texture snapshots live exactly as long as the call + promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); + } this._tail = promise.then(noop, noop); return promise; } @@ -416,6 +479,10 @@ class Pipeline { activeTrace = trace; let returned; try { + const ctorName = this.fn.constructor && this.fn.constructor.name; + if (ctorName === 'AsyncFunction' || ctorName === 'GeneratorFunction' || ctorName === 'AsyncGeneratorFunction') { + throw new Error(MSG_ASYNC_ORCHESTRATION); + } returned = this.fn.apply({ constants: Object.assign({}, this.constants) }, argHandles); } finally { activeTrace = null; @@ -432,6 +499,7 @@ class Pipeline { buffers, results, kernels, + held: trace.held, }; } @@ -490,7 +558,13 @@ class Pipeline { // (texture in the ping-pong seat, plain array from a pipeline arg) dynamicArguments: true, }; - const optional = ['constants', 'constantTypes', 'precision', 'loopMaxIterations', 'strictIntegers', 'fixIntegerDivisionAccuracy', 'optimizeFloatMemory', 'tactic', 'functions', 'nativeFunctions', 'injectedNative', 'debug']; + const optional = ['constants', 'constantTypes', 'precision', 'loopMaxIterations', 'strictIntegers', 'fixIntegerDivisionAccuracy', 'optimizeFloatMemory', 'tactic', 'functions', 'nativeFunctions', 'injectedNative', 'debug', 'randomSeed', 'returnType']; + // types the USER declared pin the clone exactly as they pin the kernel; + // types inferred by a build must not -- the clone re-infers per plan + // seat (texture in the ping-pong seat, plain array from a pipeline arg) + if (kernel.declaredArgumentTypes) { + settings.argumentTypes = kernel.declaredArgumentTypes.slice(); + } for (let i = 0; i < optional.length; i++) { const name = optional[i]; if (kernel[name] !== null && kernel[name] !== undefined) { @@ -589,6 +663,9 @@ class Pipeline { clone.destroy(); } } + if (this.plan.held) { + releaseSnapshots(this.plan.held); + } this.plan = null; } } diff --git a/test/features/pipeline/fused-webasm.js b/test/features/pipeline/fused-webasm.js index 12613571..35264356 100644 --- a/test/features/pipeline/fused-webasm.js +++ b/test/features/pipeline/fused-webasm.js @@ -1,6 +1,6 @@ const { assert, test, module: describe } = require('qunit'); const { GPU } = require('../../../src'); -const { utils } = require('../../../src/utils'); +const { utils } = require('../../../src'); describe('features: pipeline fused webasm executor'); diff --git a/test/features/pipeline/threaded-webasm.js b/test/features/pipeline/threaded-webasm.js index 5c6415ef..5fce70f0 100644 --- a/test/features/pipeline/threaded-webasm.js +++ b/test/features/pipeline/threaded-webasm.js @@ -334,6 +334,9 @@ test('Math.random draws a fresh seed per call across the pool', async assert => }); test('a dead worker rejects the run cleanly and the next call recovers', async assert => { + // browser budget: a silent-death stall (3s backstop), a full recovery + // walk, and a cpu-backend reference do not fit qunit's default 10s + assert.timeout(30000); const gpu = new GPU({ mode: 'webasm' }); const cpu = new GPU({ mode: 'cpu' }); const solve = makeJacobi(gpu, 400); @@ -342,11 +345,15 @@ test('a dead worker rejects the run cleanly and the next call recovers', async a await solve.apply(null, args); assert.equal(solve.executorKind, 'fused-threaded'); const pool = solve.pipeline._executor.pool; + // browser workers die SILENTLY on terminate (no error event), so there + // the death is only detectable as a stalled barrier -- shorten the + // backstop so both platforms reject inside the test budget + solve.pipeline._executor.sanityTimeoutMs = 3000; const doomed = solve.apply(null, args); // killed before the 400-step walk can finish: the barrier the survivors // are sitting on can never fill, and the run must reject, not hang pool.workers[0].handle.terminate(); - await assert.rejects(doomed, /worker/i, 'the in-flight run rejected with the worker death'); + await assert.rejects(doomed, /worker|stalled/i, 'the in-flight run rejected with the worker death'); const out = await solve.apply(null, args); const expected = await reference.apply(null, args); assertClose(assert, out, Array.from(expected), 'recovered results'); diff --git a/test/internal/recycling.js b/test/internal/recycling.js index 68f9d92c..bfcb3101 100644 --- a/test/internal/recycling.js +++ b/test/internal/recycling.js @@ -427,13 +427,16 @@ function testMutableLeak(mode) { pipeline: true }); kernel.build(); - const cloneTextureSpy = sinon.spy(kernel.texture.constructor.prototype, 'beforeMutate'); + // the leak signal is a NEW texture being made per run -- beforeMutate + // itself now runs every render as the refs check that keeps clone() + // honest on mutable kernels, and is a no-op when nothing was cloned + const newTextureSpy = sinon.spy(kernel.texture.constructor.prototype, 'newTexture'); const texture1 = kernel(); const texture2 = kernel(); - assert.equal(cloneTextureSpy.callCount, 0); + assert.equal(newTextureSpy.callCount, 0); assert.equal(texture1.texture._refs, 1); assert.ok(texture1 === texture2); - cloneTextureSpy.restore(); + newTextureSpy.restore(); gpu.destroy(); } From d87e4ad5920f5419114f4bf012af69c48298c420 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 14:29:04 +0800 Subject: [PATCH 07/16] docs(pipeline): final benchmark numbers after the review fixes Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 2 +- dist/gpu-browser-core.js | 2 +- dist/gpu-browser-core.min.js | 2 +- dist/gpu-browser.js | 2 +- dist/gpu-browser.min.js | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5bac628d..2450b5aa 100644 --- a/README.md +++ b/README.md @@ -1391,7 +1391,7 @@ Calling a pipeline **always returns a Promise** — the [async contract](#asynch Every backend runs pipelines. The reference path (`executorKind: 'generic'`) walks the plan through the normal kernel machinery — private per-pipeline kernel instances with `pipeline: true` forced on, your kernel's settings never observably touched — so on GL it is textures end-to-end. On **webasm** the plan *fuses*: every step compiles over one shared `WebAssembly.Memory` laid out `[pipeline args | plan buffers]`, passes run back-to-back with intermediates never copied out between steps (`'fused-sync'`), and where wasm threads are available the worker pool executes the *whole plan* per worker with Atomics-based barriers between steps — one dispatch per pipeline call, no main-thread round trip per pass (`'fused-threaded'`). Anything the webasm backend cannot take degrades to the generic executor under its usual contract: the reason is queryable at `pipeline.fallbackReason`, and `pipeline.executorKind` tells you which executor actually ran. -What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): **3.3× on heat threaded, 5.3× on jacobi** (400 ms vs 2137 ms per-pass; heat 1321 ms vs 4310 ms), against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. +What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): **5.7× on heat threaded, 5.2× on jacobi** (heat 890 ms vs 5073 ms per-pass, jacobi 387 ms vs 1997 ms — and 2.8×/3.2× over plain JavaScript on rows the webasm backend previously lost), against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. Not in v1, stated plainly: diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 8bb346c8..b221dc08 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:29:02 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 52a88c3c..d414f039 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:29:02 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index b09b05ed..6342a774 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:29:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 11b1f599..1a5d5287 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:20:55 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:29:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License From 8e716bd6ca5416f61fdfdfbb68aacac840c8fe59 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 14:39:59 +0800 Subject: [PATCH 08/16] test(pipeline): run the correctness matrix on webgpu The pipeline test files never enumerated webgpu, so the generic executor's webgpu path (async kernel runs, async buffer-handle readback) had never executed. Every eachMode scenario now has a browser-only webgpu row pinned to executorKind 'generic', gated on GPU.isWebGPUSupported with the adapterless runtime-skip convention of test/features/webgpu, plus a row proving the fused compile declines webgpu on its own with fallbackReason, and a webgpu variant of the non-adjacent-liveness buffer test. Both awaits in _executeGeneric are proven load-bearing: removing either fails these rows on real WebGPU (headed ANGLE Metal). Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 2 +- dist/gpu-browser-core.min.js | 2 +- dist/gpu-browser.js | 2 +- dist/gpu-browser.min.js | 2 +- test/features/pipeline/buffers.js | 23 +++++++++- test/features/pipeline/correctness.js | 62 ++++++++++++++++++++++----- 6 files changed, 77 insertions(+), 16 deletions(-) diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index b221dc08..da2e2eef 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:29:02 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index d414f039..8680eff8 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:29:02 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index 6342a774..5cacf3f5 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:29:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 1a5d5287..f6a2c1fd 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:29:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/test/features/pipeline/buffers.js b/test/features/pipeline/buffers.js index fd78cc9a..713ab1de 100644 --- a/test/features/pipeline/buffers.js +++ b/test/features/pipeline/buffers.js @@ -75,7 +75,7 @@ function livenessKeepsEarlyOutputAlive(mode) { const plan = solve.plan; assert.equal(plan.buffers.length, 3, 'step 1 output kept alive in its own slot'); assert.notEqual(plan.steps[1].outputBuffer, plan.steps[0].outputBuffer, 'the middle step did not overwrite it'); - gpu.destroy(); + await gpu.destroy(); }; } @@ -83,6 +83,27 @@ test('liveness keeps a non-adjacent output alive cpu', livenessKeepsEarlyOutputA test('liveness keeps a non-adjacent output alive webasm', livenessKeepsEarlyOutputAlive('webasm')); (GPU.isHeadlessGLSupported ? test : skip)('liveness keeps a non-adjacent output alive headlessgl', livenessKeepsEarlyOutputAlive('headlessgl')); +// navigator.gpu can be present with no adapter (headless Chromium, blocklisted +// GPUs); QUnit cannot skip at runtime, so an adapterless environment records a +// pass with an explicit message and bumps a counter the headed canary rejects. +let adapterPromise = null; +async function webgpuAdapter(assert) { + if (!adapterPromise) adapterPromise = navigator.gpu.requestAdapter(); + const adapter = await adapterPromise; + if (!adapter) { + if (typeof window !== 'undefined') { + window.__webgpuRuntimeSkips = (window.__webgpuRuntimeSkips || 0) + 1; + } + assert.ok(true, 'navigator.gpu present but no adapter (headless/blocklisted) — runtime skip'); + } + return adapter; +} + +(GPU.isWebGPUSupported ? test : skip)('liveness keeps a non-adjacent output alive webgpu', async assert => { + if (!(await webgpuAdapter(assert))) return; + return livenessKeepsEarlyOutputAlive('webgpu')(assert); +}); + test('slots are only shared between steps of identical output shape', async assert => { const gpu = new GPU({ mode: 'cpu' }); const wide = gpu.createKernel(function (u) { diff --git a/test/features/pipeline/correctness.js b/test/features/pipeline/correctness.js index bbe31f70..a8513066 100644 --- a/test/features/pipeline/correctness.js +++ b/test/features/pipeline/correctness.js @@ -4,10 +4,12 @@ const { GPU } = require('../../../src'); describe('features: pipeline correctness'); // Every scenario runs against a plain-JS reference on every backend -// available here (cpu, webasm, and headlessgl where supported). executorKind -// is asserted per mode: webasm compiles these plans to the fused executor, -// and a forced-generic webasm variant keeps the correctness-reference -// executor covered on that backend too. +// available here (cpu, webasm, headlessgl where supported, and webgpu in a +// browser with an adapter). executorKind is asserted per mode: webasm +// compiles these plans to the fused executor, and a forced-generic webasm +// variant keeps the correctness-reference executor covered on that backend +// too. webgpu has no fused lowering in v1, so its rows pin the generic +// executor over buffer-handle intermediates. function assertClose(assert, actual, expected, label) { const values = Array.from(actual); @@ -19,11 +21,31 @@ function assertClose(assert, actual, expected, label) { } } +// navigator.gpu can be present with no adapter (headless Chromium, blocklisted +// GPUs); QUnit cannot skip at runtime, so an adapterless environment records a +// pass with an explicit message and bumps a counter the headed canary rejects. +let adapterPromise = null; +async function webgpuAdapter(assert) { + if (!adapterPromise) adapterPromise = navigator.gpu.requestAdapter(); + const adapter = await adapterPromise; + if (!adapter) { + if (typeof window !== 'undefined') { + window.__webgpuRuntimeSkips = (window.__webgpuRuntimeSkips || 0) + 1; + } + assert.ok(true, 'navigator.gpu present but no adapter (headless/blocklisted) — runtime skip'); + } + return adapter; +} + function eachMode(name, body) { test(`${ name } cpu`, assert => body(assert, 'cpu', 'generic')); test(`${ name } webasm`, assert => body(assert, 'webasm', 'fused-sync')); test(`${ name } webasm (generic forced)`, assert => body(assert, 'webasm', 'generic')); (GPU.isHeadlessGLSupported ? test : skip)(`${ name } headlessgl`, assert => body(assert, 'headlessgl', 'generic')); + (GPU.isWebGPUSupported ? test : skip)(`${ name } webgpu`, async assert => { + if (!(await webgpuAdapter(assert))) return; + return body(assert, 'webgpu', 'generic'); + }); } // the test/benchmark hook: fusion is skipped entirely, the plan runs generic @@ -60,7 +82,7 @@ eachMode('jacobi-like ping-pong through one kernel', async (assert, mode, kind) } assert.equal(solve.executorKind, kind, `runs the ${ kind } executor`); assertClose(assert, result, expected, 'jacobi'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('multi-kernel chain', async (assert, mode, kind) => { @@ -86,7 +108,7 @@ eachMode('multi-kernel chain', async (assert, mode, kind) => { const expected = x.map(v => (v * 2 + 1) * (v * 2)); assert.equal(chain.executorKind, kind); assertClose(assert, result, expected, 'chain'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('multi-output object return', async (assert, mode, kind) => { @@ -111,7 +133,7 @@ eachMode('multi-output object return', async (assert, mode, kind) => { assert.deepEqual(Object.keys(result).sort(), ['doubled', 'negated'], 'resolves to the same object shape'); assertClose(assert, result.doubled, [2, 4, 6, 8], 'doubled'); assertClose(assert, result.negated, [-1, -2, -3, -4], 'negated'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('array return resolves to an array of plain results', async (assert, mode, kind) => { @@ -129,7 +151,7 @@ eachMode('array return resolves to an array of plain results', async (assert, mo assert.equal(result.length, 2); assertClose(assert, result[0], [2, 4, 6, 8], 'first'); assertClose(assert, result[1], [4, 8, 12, 16], 'second'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('literal and closure-captured kernel arguments', async (assert, mode, kind) => { @@ -149,7 +171,7 @@ eachMode('literal and closure-captured kernel arguments', async (assert, mode, k const result = await solve([1, 2, 3, 4]); assert.equal(solve.executorKind, kind); assertClose(assert, result, [13, 26, 39, 52], 'literal scalar and captured array'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('pipeline arg reused by several steps', async (assert, mode, kind) => { @@ -167,7 +189,7 @@ eachMode('pipeline arg reused by several steps', async (assert, mode, kind) => { const result = await solve([1, 2, 3, 4], [10, 10, 10, 10]); assert.equal(solve.executorKind, kind); assertClose(assert, result, [31, 32, 33, 34], 'q consumed by three steps'); - gpu.destroy(); + await gpu.destroy(); }); eachMode('2d output kernels', async (assert, mode, kind) => { @@ -188,5 +210,23 @@ eachMode('2d output kernels', async (assert, mode, kind) => { assert.equal(result.length, 2, '2d shape survives readback'); assertClose(assert, result[0], [3, 4, 5], 'row 0'); assertClose(assert, result[1], [13, 14, 15], 'row 1'); - gpu.destroy(); + await gpu.destroy(); +}); + +// the rows above force the generic executor; this one leaves fusion enabled +// so the webasm-only fused compile must decline webgpu by itself +(GPU.isWebGPUSupported ? test : skip)('webgpu degrades naturally to the generic executor', async assert => { + if (!(await webgpuAdapter(assert))) return; + const gpu = new GPU({ mode: 'webgpu' }); + const double = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4] }); + const solve = gpu.createPipeline(function (x) { + return double(double(x)); + }); + const result = await solve([1, 2, 3, 4]); + assert.equal(solve.executorKind, 'generic', 'no fused lowering for webgpu in v1'); + assert.ok(/webgpu/.test(solve.fallbackReason), `fallbackReason names the backend: ${ solve.fallbackReason }`); + assertClose(assert, result, [4, 8, 12, 16], 'degraded run is still correct'); + await gpu.destroy(); }); From 7f7edc529a8ca44209d48774dc822924a36471f8 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 15:01:27 +0800 Subject: [PATCH 09/16] feat: webgpu fused-encoder pipeline executor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lower compiled pipeline plans on webgpu to one command encoder: every plan step builds through WebGPUKernel's own WGSL machinery, then runs against persistent storage buffers — ping-pong steps land on static alternating bind groups, per-step params uniforms are created at compile. Per call: pipeline args and per-call scalars/seeds go up via queue.writeBuffer, every step records as a compute pass into ONE encoder, results copy to a single MAP_READ staging buffer in the same encoder, one submit, one mapAsync readback. Seeded Math.random keeps the direct-call contract (per-step draw when unpinned, baked when pinned); argument size/type drift recompiles like the webasm executor; GPU-resident handle arguments and vec intermediates degrade to the generic executor with a named fallbackReason. Also fixes call-time sampling of Input pipeline arguments: Input has a toArray(), so the texture duck-type branch in snapshotValue swallowed it before the copy (and the encoder's handle check declined it). Jacobi 512x512, 512 sweeps, one call (ANGLE Metal): generic ~118ms, fused-encoder ~11ms, identical checksums. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 3 +- dist/gpu-browser-core.js | 488 +++++++++++++++++- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 488 +++++++++++++++++- dist/gpu-browser.min.js | 4 +- docs/design/pipeline-compilation.md | 14 +- src/backend/web-gpu/pipeline-executor.js | 609 +++++++++++++++++++++++ src/index.d.ts | 3 +- src/pipeline.js | 40 +- test/all.html | 1 + test/features/pipeline/correctness.js | 15 +- test/features/pipeline/fused-webgpu.js | 411 +++++++++++++++ 12 files changed, 2037 insertions(+), 43 deletions(-) create mode 100644 src/backend/web-gpu/pipeline-executor.js create mode 100644 test/features/pipeline/fused-webgpu.js diff --git a/README.md b/README.md index 2450b5aa..e779a0fc 100644 --- a/README.md +++ b/README.md @@ -1398,9 +1398,10 @@ Not in v1, stated plainly: * **No mid-plan readback.** The plan runs start to finish; you cannot inspect an intermediate and stop early. The name `this.check` on the orchestration context is **reserved** for this: the future design records `this.check(handle, predicate)` as a checkpoint step where the executor reads back a small reduction every N passes and ends the plan early when the predicate answers converged — residual thresholds in iterative solvers, without surrendering the fused loop. Nothing you write today should put a `check` on the orchestration `this`. * **No graphical kernels inside pipelines** — throws at build. * **No kernel maps inside pipelines** — throws at build. -* **No webgpu command-encoder lowering** — webgpu runs pipelines through the generic executor (correct, one readback, but one submit per step); single-encoder lowering is future work. * **`toString()` is deferred** — a pipeline cannot be exported as source yet. +On webgpu, pipelines compile to the `fused-encoder` executor: every step is recorded as a compute pass into ONE command encoder over persistent storage buffers (ping-pong steps alternate between two static bind groups), one `queue.submit` runs the whole plan, and the results come back through a single `mapAsync` readback. Anything the encoder cannot take statically — GPU-resident handles as pipeline arguments, vector-returning intermediates — degrades to the generic executor with the reason in `fallbackReason`. + ## Asynchronous Kernels **New in 2.20.0!** diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index da2e2eef..4c65b0a8 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -19114,7 +19114,7 @@ } }; }); - var require_pipeline_executor = __commonJSMin((exports, module) => { + var require_pipeline_executor$1 = __commonJSMin((exports, module) => { const {utils: utils} = require_utils(); const {Input: Input} = require_input(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); @@ -19691,6 +19691,465 @@ FusionFallback: FusionFallback }; }); + var require_pipeline_executor = __commonJSMin((exports, module) => { + const {utils: utils} = require_utils(); + const {Input: Input} = require_input(); + const {FusionFallback: FusionFallback} = require_pipeline_executor$1(); + const USAGE_STORAGE = 128; + const MAP_MODE_READ = 1; + function valueDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function scalarMatches(type, value) { + switch (type) { + case "Integer": + return typeof value === "number" && Number.isInteger(value); + + case "Boolean": + return typeof value === "boolean"; + + default: + return typeof value === "number"; + } + } + function isResidentHandle(value) { + return Boolean(value) && typeof value === "object" && !(value instanceof Input) && (typeof value.toArray === "function" || typeof value.delete === "function"); + } + function align16(value) { + return Math.ceil(value / 16) * 16; + } + module.exports = { + WebGPUPipelineExecutor: class WebGPUPipelineExecutor { + static async compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== "webgpu") throw new FusionFallback(`pipeline backend is ${kernel.constructor.mode}; the fused encoder requires webgpu`); + } + if (plan.steps.length === 0) throw new FusionFallback("plan has no kernel steps to fuse"); + const executor = new WebGPUPipelineExecutor(pipeline, plan); + try { + await executor._compile(args); + } catch (e) { + executor.destroy(); + throw e; + } + return executor; + } + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = "fused-encoder"; + this.destroyed = false; + this.context = null; + this._device = null; + this._planBuffers = null; + this._argRegions = new Map; + this._argScalarSlots = new Map; + this._literalBuffers = new Map; + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + this._staging = null; + this._extraShortcuts = []; + this._scratch = new Map; + } + async _compile(args) { + const plan = this.plan; + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "pipelineArg" && isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); + } + } + const programs = new Map; + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ":" + reps.map(value => utils.getVariableType(value, strict)).join(","); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + const extra = this.pipeline._cloneKernel(kernelEntry.clone); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + await this._prepareKernel(kernel, reps); + program = { + id: programs.size, + kernel: kernel + }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + } + this._scratch = null; + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step" && stepPrograms[binding.step].kernel.componentCount !== 1) throw new FusionFallback(`a step returning ${stepPrograms[binding.step].kernel.returnType} cannot feed another step in the fused encoder`); + } + } + const device = this._device = stepPrograms[0].kernel._device; + this.context = stepPrograms[0].kernel.context; + const queue = device.queue; + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + this._planBuffers = plan.buffers.map((record, b) => { + const dims = record.output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + return { + cells: cells, + buffer: device.createBuffer({ + size: cells * bufferComponents[b] * 4, + usage: 132 + }) + }; + }); + const bufferIds = new Map; + const idOf = buffer => { + let id = bufferIds.get(buffer); + if (id === void 0) { + id = bufferIds.size; + bufferIds.set(buffer, id); + } + return id; + }; + const passRecords = new Map; + this._passes = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const kernel = program.kernel; + const layout = kernel.paramsLayout; + const argBuffers = new Array(layout.arrayArgs.length); + const argDims = new Array(layout.arrayArgs.length); + for (let j = 0; j < layout.arrayArgs.length; j++) { + const record = layout.arrayArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === "pipelineArg") { + let region = this._argRegions.get(binding.index); + if (!region) { + const dims = valueDimensions(args[binding.index]); + const flatLength = dims[0] * dims[1] * dims[2]; + region = { + dims: dims, + flatLength: flatLength, + scratch: new Float32Array(flatLength), + buffer: device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: 136 + }) + }; + this._argRegions.set(binding.index, region); + } + argBuffers[j] = region.buffer; + argDims[j] = region.dims; + } else if (binding.source === "literal") { + let literal = this._literalBuffers.get(binding.value); + if (!literal) { + const dims = valueDimensions(binding.value); + const flatLength = dims[0] * dims[1] * dims[2]; + const buffer = device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: USAGE_STORAGE, + mappedAtCreation: true + }); + const mapped = new Float32Array(buffer.getMappedRange()); + utils.flattenTo(binding.value instanceof Input ? binding.value.value : binding.value, mapped.subarray(0, flatLength)); + buffer.unmap(); + literal = { + buffer: buffer, + dims: dims + }; + this._literalBuffers.set(binding.value, literal); + } + argBuffers[j] = literal.buffer; + argDims[j] = literal.dims; + } else { + const producer = plan.steps[binding.step]; + const dims = Array.from(producer.output); + while (dims.length < 3) dims.push(1); + argBuffers[j] = this._planBuffers[producer.outputBuffer].buffer; + argDims[j] = dims; + } + } + const outputBuffer = this._planBuffers[step.outputBuffer].buffer; + const scalarSignature = layout.scalarArgs.map(record => { + const binding = step.argBindings[record.index]; + return binding.source === "literal" ? "l" + binding.value : "a" + binding.index; + }).join(","); + const unpinnedRandom = layout.randomSeedOffset !== null && kernel.randomSeed === null; + const key = program.id + ":" + argBuffers.map(idOf).join(",") + ">" + idOf(outputBuffer) + ":" + scalarSignature + (unpinnedRandom ? "#" + i : ""); + let stepPass = passRecords.get(key); + if (!stepPass) { + const mirror = new ArrayBuffer(layout.byteLength); + const u32 = new Uint32Array(mirror); + const i32 = new Int32Array(mirror); + const f32 = new Float32Array(mirror); + const dispatch = kernel._computeDispatch(kernel.threadDim); + u32[0] = kernel.threadDim[0]; + u32[1] = kernel.threadDim[1]; + u32[2] = kernel.threadDim[2]; + u32[3] = dispatch.dispatchWidth; + for (let j = 0; j < layout.arrayArgs.length; j++) { + const base = layout.arrayArgs[j].dimsOffset / 4; + u32[base] = argDims[j][0]; + u32[base + 1] = argDims[j][1]; + u32[base + 2] = argDims[j][2]; + u32[base + 3] = argDims[j][0] * argDims[j][1] * argDims[j][2]; + } + const perCallScalars = []; + for (let j = 0; j < layout.scalarArgs.length; j++) { + const record = layout.scalarArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === "literal") this._writeScalar(u32, i32, f32, record, binding.value); else if (binding.source === "pipelineArg") { + perCallScalars.push({ + index: binding.index, + offset: record.offset, + type: record.type + }); + this._argScalarSlots.set(binding.index + ":" + record.type, { + index: binding.index, + type: record.type + }); + } else throw new FusionFallback("a step output cannot bind to a scalar argument"); + } + if (layout.randomSeedOffset !== null && kernel.randomSeed !== null) u32[layout.randomSeedOffset / 4] = kernel.randomSeed >>> 0; + const paramsBuffer = device.createBuffer({ + size: layout.byteLength, + usage: 72 + }); + const perCall = perCallScalars.length > 0 || unpinnedRandom; + if (!perCall) queue.writeBuffer(paramsBuffer, 0, mirror); + const entries = [ { + binding: 0, + resource: { + buffer: paramsBuffer + } + } ]; + for (let j = 0; j < argBuffers.length; j++) entries.push({ + binding: 1 + j, + resource: { + buffer: argBuffers[j] + } + }); + const outBinding = 1 + argBuffers.length; + entries.push({ + binding: outBinding, + resource: { + buffer: outputBuffer + } + }); + for (let j = 0; j < layout.bufferConstants.length; j++) entries.push({ + binding: outBinding + 1 + j, + resource: { + buffer: layout.bufferConstants[j].buffer + } + }); + stepPass = { + pipeline: kernel.computePipeline, + bindGroup: device.createBindGroup({ + layout: kernel.bindGroupLayout, + entries: entries + }), + groups: dispatch.groups, + paramsBuffer: paramsBuffer, + mirror: mirror, + u32: u32, + i32: i32, + f32: f32, + perCall: perCall, + perCallScalars: perCallScalars, + seedOffset: unpinnedRandom ? layout.randomSeedOffset : null + }; + this._paramsRecords.push(stepPass); + passRecords.set(key, stepPass); + } + this._passes[i] = stepPass; + } + let stagingBytes = 0; + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === "step") { + const step = plan.steps[binding.step]; + const planBuffer = this._planBuffers[step.outputBuffer]; + const kernel = stepPrograms[binding.step].kernel; + const byteLength = planBuffer.cells * kernel.componentCount * 4; + const read = { + kind: "step", + buffer: planBuffer.buffer, + offset: stagingBytes, + byteLength: byteLength, + output: step.output, + componentCount: kernel.componentCount, + kernel: kernel + }; + stagingBytes += align16(byteLength); + return read; + } + if (binding.source === "pipelineArg") return { + kind: "arg", + index: binding.index + }; + return { + kind: "literal", + value: binding.value + }; + }); + if (stagingBytes > 0) this._staging = device.createBuffer({ + size: stagingBytes, + usage: 9 + }); + } + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === "pipelineArg") reps[j] = args[binding.index]; else if (binding.source === "literal") reps[j] = binding.value; else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + async _prepareKernel(kernel, reps) { + if (kernel.built || kernel._buildPromise) { + const gpuKernels = kernel.gpu && kernel.gpu.kernels; + kernel.destroy(); + if (gpuKernels && gpuKernels.indexOf(kernel) === -1) gpuKernels.push(kernel); + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; + } + await kernel.build.apply(kernel, reps); + if (kernel.outputBuffer) { + if (--kernel.outputBuffer._refs === 0) kernel.outputBuffer.destroy(); + kernel.outputBuffer = null; + } + } + _checkArguments(args) { + for (const [index, region] of this._argRegions) { + const value = args[index]; + if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + if (isResidentHandle(value)) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); + } + for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + } + _writeScalar(u32, i32, f32, record, value) { + const slot = record.offset / 4; + if (record.type === "Integer") i32[slot] = value | 0; else if (record.type === "Boolean") u32[slot] = value ? 1 : 0; else f32[slot] = value; + } + execute(args) { + if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + if (this.context && this.context.isLost) return Promise.reject(new Error("WebGPU device was lost; the pipeline will rebuild on a fresh device on its next call")); + this._checkArguments(args); + const device = this._device; + const queue = device.queue; + for (const [index, region] of this._argRegions) { + const value = args[index]; + utils.flattenTo(value instanceof Input ? value.value : value, region.scratch); + queue.writeBuffer(region.buffer, 0, region.scratch); + } + for (let i = 0; i < this._paramsRecords.length; i++) { + const record = this._paramsRecords[i]; + if (!record.perCall) continue; + for (let j = 0; j < record.perCallScalars.length; j++) { + const slot = record.perCallScalars[j]; + this._writeScalar(record.u32, record.i32, record.f32, slot, args[slot.index]); + } + if (record.seedOffset !== null) record.u32[record.seedOffset / 4] = Math.random() * 4294967296 >>> 0; + queue.writeBuffer(record.paramsBuffer, 0, record.mirror); + } + const encoder = device.createCommandEncoder(); + for (let i = 0; i < this._passes.length; i++) { + const stepPass = this._passes[i]; + const pass = encoder.beginComputePass(); + pass.setPipeline(stepPass.pipeline); + pass.setBindGroup(0, stepPass.bindGroup); + pass.dispatchWorkgroups(stepPass.groups[0], stepPass.groups[1], stepPass.groups[2]); + pass.end(); + } + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") encoder.copyBufferToBuffer(read.buffer, 0, this._staging, read.offset, read.byteLength); + } + queue.submit([ encoder.finish() ]); + if (!this._staging) return Promise.resolve(this._shapeResults(args, null)); + return this._staging.mapAsync(MAP_MODE_READ).then(() => { + const mapped = this._staging.getMappedRange(); + const values = this._shapeResults(args, mapped); + this._staging.unmap(); + return values; + }); + } + _shapeResults(args, mapped) { + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") { + const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } + destroy() { + if (this.destroyed) return; + this.destroyed = true; + if (this._planBuffers) for (let i = 0; i < this._planBuffers.length; i++) this._planBuffers[i].buffer.destroy(); + for (const region of this._argRegions.values()) region.buffer.destroy(); + for (const literal of this._literalBuffers.values()) literal.buffer.destroy(); + for (let i = 0; i < this._paramsRecords.length; i++) this._paramsRecords[i].paramsBuffer.destroy(); + if (this._staging) { + this._staging.destroy(); + this._staging = null; + } + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); + } + this._extraShortcuts = []; + this._planBuffers = null; + this._argRegions = new Map; + this._argScalarSlots = new Map; + this._literalBuffers = new Map; + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + } + } + }; + }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; @@ -19782,6 +20241,7 @@ }; function snapshotValue(value, held) { if (!value || typeof value !== "object") return value; + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); if (typeof value.delete === "function" || typeof value.toArray === "function") { if (typeof value.clone === "function" && held) { const cloned = value.clone(); @@ -19792,7 +20252,6 @@ } if (ArrayBuffer.isView(value)) return value.slice(0); if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); - if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } function releaseSnapshots(held) { @@ -19897,22 +20356,22 @@ const sampled = new Array(args.length); const held = []; for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); - const promise = this._tail.then(() => { + const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { this.plan = this._buildPlan(); this._executor = void 0; } - if (this._executor === void 0) this._prepareExecutor(sampled); + if (this._executor === void 0) await this._prepareExecutor(sampled); if (this._executor) try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); if (e.recompilable) { - this._prepareExecutor(sampled); + await this._prepareExecutor(sampled); if (this._executor) try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -19997,8 +20456,19 @@ this._executor = false; return; } + const kernels = this.plan.kernels; + if (kernels.length > 0 && kernels[0].clone.kernel.constructor.mode === "webgpu") { + const {WebGPUPipelineExecutor: WebGPUPipelineExecutor} = require_pipeline_executor(); + return WebGPUPipelineExecutor.compile(this, this.plan, args).then(executor => { + this._executor = executor; + this.executorKind = executor.kind; + this.fallbackReason = null; + }, e => { + this._degrade(e && e.message || "fused executor unavailable"); + }); + } try { - const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor(); + const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor$1(); this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); this.executorKind = this._executor.kind; this.fallbackReason = null; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 8680eff8..35028c5c 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,E=new Array(s.length),I={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,r)=>{B.assignArgumentType(e,t,r)},L=(e,t,r)=>B.lookupReturnType(e,t,r),F=e=>B.lookupFunctionArgumentTypes(e),$=(e,t)=>B.lookupFunctionArgumentName(e,t),D=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),C=(e,t,r,n)=>{B.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{B.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{B.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:I,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:D,needsArgumentType:_,assignArgumentType:k,triggerImplyArgumentType:C,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let U=null;b&&(U=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:U});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),D=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),C=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:C}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:O}=I(),{GLTextureMemoryOptimized2D:N}=_(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:U}=F(),{GLTextureUnsigned3D:B}=$(),{GLTextureGraphical:K}=D();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=U,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=U,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=C,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return I}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${E(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${E(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${E(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function E(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function I(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:D,kernelConstants:C,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:E,functions:I,nativeFunctions:_,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return C.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),U=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),B=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=U();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=U(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=U();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:E}=pe(),{WebGLKernelValueArray3:I}=de(),{WebGLKernelValueArray4:_}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":E,"Array(3)":I,"Array(4)":_,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=C(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=B();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),_e=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=_e();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=De();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Be();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=_e(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=De(),{WebGL2KernelValueDynamicSingleInput:p}=Ce(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Ue(),{WebGL2KernelValueSingleArray1DI:T}=Be(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:E}=je(),{WebGL2KernelValueDynamicSingleArray3DI:I}=qe(),{WebGL2KernelValueArray2:_}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),D={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":I,"Array3D(3)":I,"Array3D(4)":I,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":_,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:D,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=D[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=I.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:E},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),I.set(o,l)}_[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:_.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=_,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e instanceof r?new r(p(e.value,t),e.size):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ht();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),pt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=ct(),{Pipeline:g}=ht(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),ft=e((e,t)=>{const{GPU:r}=pt(),{alias:c}=dt(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:E}=ve(),{WebGL2Kernel:I}=et(),{kernelValueMaps:_}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:D}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=C(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:E,WebGL2Kernel:I,webGL2KernelValueMaps:_,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:D,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=ft(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function u(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function l(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}u[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=d.get(e);return void 0===t&&(t=d.size,d.set(e,t)),t},m=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),v=null!==d.randomSeedOffset&&null===p.randomSeed,T=l.id+":"+g.map(f).join(",")+">"+f(x)+":"+b+(v?"#"+n:"");let S=m.get(T);if(!S){const e=new ArrayBuffer(d.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=p._computeDispatch(p.threadDim);t[0]=p.threadDim[0],t[1]=p.threadDim[1],t[2]=p.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:d.byteLength,usage:72}),l=o.length>0||v;l||c.writeBuffer(u,0,e);const f=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=u[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:g,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return g+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),g>0&&(this._staging=h.createBuffer({size:g,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index 5cacf3f5..b37d4622 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -23311,7 +23311,7 @@ } }; }); - var require_pipeline_executor = __commonJSMin((exports, module) => { + var require_pipeline_executor$1 = __commonJSMin((exports, module) => { const {utils: utils} = require_utils(); const {Input: Input} = require_input(); const {WebAssemblyKernel: WebAssemblyKernel} = require_kernel(); @@ -23888,6 +23888,465 @@ FusionFallback: FusionFallback }; }); + var require_pipeline_executor = __commonJSMin((exports, module) => { + const {utils: utils} = require_utils(); + const {Input: Input} = require_input(); + const {FusionFallback: FusionFallback} = require_pipeline_executor$1(); + const USAGE_STORAGE = 128; + const MAP_MODE_READ = 1; + function valueDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function scalarMatches(type, value) { + switch (type) { + case "Integer": + return typeof value === "number" && Number.isInteger(value); + + case "Boolean": + return typeof value === "boolean"; + + default: + return typeof value === "number"; + } + } + function isResidentHandle(value) { + return Boolean(value) && typeof value === "object" && !(value instanceof Input) && (typeof value.toArray === "function" || typeof value.delete === "function"); + } + function align16(value) { + return Math.ceil(value / 16) * 16; + } + module.exports = { + WebGPUPipelineExecutor: class WebGPUPipelineExecutor { + static async compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== "webgpu") throw new FusionFallback(`pipeline backend is ${kernel.constructor.mode}; the fused encoder requires webgpu`); + } + if (plan.steps.length === 0) throw new FusionFallback("plan has no kernel steps to fuse"); + const executor = new WebGPUPipelineExecutor(pipeline, plan); + try { + await executor._compile(args); + } catch (e) { + executor.destroy(); + throw e; + } + return executor; + } + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = "fused-encoder"; + this.destroyed = false; + this.context = null; + this._device = null; + this._planBuffers = null; + this._argRegions = new Map; + this._argScalarSlots = new Map; + this._literalBuffers = new Map; + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + this._staging = null; + this._extraShortcuts = []; + this._scratch = new Map; + } + async _compile(args) { + const plan = this.plan; + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "pipelineArg" && isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); + } + } + const programs = new Map; + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ":" + reps.map(value => utils.getVariableType(value, strict)).join(","); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + const extra = this.pipeline._cloneKernel(kernelEntry.clone); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + await this._prepareKernel(kernel, reps); + program = { + id: programs.size, + kernel: kernel + }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + } + this._scratch = null; + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === "step" && stepPrograms[binding.step].kernel.componentCount !== 1) throw new FusionFallback(`a step returning ${stepPrograms[binding.step].kernel.returnType} cannot feed another step in the fused encoder`); + } + } + const device = this._device = stepPrograms[0].kernel._device; + this.context = stepPrograms[0].kernel.context; + const queue = device.queue; + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + this._planBuffers = plan.buffers.map((record, b) => { + const dims = record.output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + return { + cells: cells, + buffer: device.createBuffer({ + size: cells * bufferComponents[b] * 4, + usage: 132 + }) + }; + }); + const bufferIds = new Map; + const idOf = buffer => { + let id = bufferIds.get(buffer); + if (id === void 0) { + id = bufferIds.size; + bufferIds.set(buffer, id); + } + return id; + }; + const passRecords = new Map; + this._passes = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const kernel = program.kernel; + const layout = kernel.paramsLayout; + const argBuffers = new Array(layout.arrayArgs.length); + const argDims = new Array(layout.arrayArgs.length); + for (let j = 0; j < layout.arrayArgs.length; j++) { + const record = layout.arrayArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === "pipelineArg") { + let region = this._argRegions.get(binding.index); + if (!region) { + const dims = valueDimensions(args[binding.index]); + const flatLength = dims[0] * dims[1] * dims[2]; + region = { + dims: dims, + flatLength: flatLength, + scratch: new Float32Array(flatLength), + buffer: device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: 136 + }) + }; + this._argRegions.set(binding.index, region); + } + argBuffers[j] = region.buffer; + argDims[j] = region.dims; + } else if (binding.source === "literal") { + let literal = this._literalBuffers.get(binding.value); + if (!literal) { + const dims = valueDimensions(binding.value); + const flatLength = dims[0] * dims[1] * dims[2]; + const buffer = device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: USAGE_STORAGE, + mappedAtCreation: true + }); + const mapped = new Float32Array(buffer.getMappedRange()); + utils.flattenTo(binding.value instanceof Input ? binding.value.value : binding.value, mapped.subarray(0, flatLength)); + buffer.unmap(); + literal = { + buffer: buffer, + dims: dims + }; + this._literalBuffers.set(binding.value, literal); + } + argBuffers[j] = literal.buffer; + argDims[j] = literal.dims; + } else { + const producer = plan.steps[binding.step]; + const dims = Array.from(producer.output); + while (dims.length < 3) dims.push(1); + argBuffers[j] = this._planBuffers[producer.outputBuffer].buffer; + argDims[j] = dims; + } + } + const outputBuffer = this._planBuffers[step.outputBuffer].buffer; + const scalarSignature = layout.scalarArgs.map(record => { + const binding = step.argBindings[record.index]; + return binding.source === "literal" ? "l" + binding.value : "a" + binding.index; + }).join(","); + const unpinnedRandom = layout.randomSeedOffset !== null && kernel.randomSeed === null; + const key = program.id + ":" + argBuffers.map(idOf).join(",") + ">" + idOf(outputBuffer) + ":" + scalarSignature + (unpinnedRandom ? "#" + i : ""); + let stepPass = passRecords.get(key); + if (!stepPass) { + const mirror = new ArrayBuffer(layout.byteLength); + const u32 = new Uint32Array(mirror); + const i32 = new Int32Array(mirror); + const f32 = new Float32Array(mirror); + const dispatch = kernel._computeDispatch(kernel.threadDim); + u32[0] = kernel.threadDim[0]; + u32[1] = kernel.threadDim[1]; + u32[2] = kernel.threadDim[2]; + u32[3] = dispatch.dispatchWidth; + for (let j = 0; j < layout.arrayArgs.length; j++) { + const base = layout.arrayArgs[j].dimsOffset / 4; + u32[base] = argDims[j][0]; + u32[base + 1] = argDims[j][1]; + u32[base + 2] = argDims[j][2]; + u32[base + 3] = argDims[j][0] * argDims[j][1] * argDims[j][2]; + } + const perCallScalars = []; + for (let j = 0; j < layout.scalarArgs.length; j++) { + const record = layout.scalarArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === "literal") this._writeScalar(u32, i32, f32, record, binding.value); else if (binding.source === "pipelineArg") { + perCallScalars.push({ + index: binding.index, + offset: record.offset, + type: record.type + }); + this._argScalarSlots.set(binding.index + ":" + record.type, { + index: binding.index, + type: record.type + }); + } else throw new FusionFallback("a step output cannot bind to a scalar argument"); + } + if (layout.randomSeedOffset !== null && kernel.randomSeed !== null) u32[layout.randomSeedOffset / 4] = kernel.randomSeed >>> 0; + const paramsBuffer = device.createBuffer({ + size: layout.byteLength, + usage: 72 + }); + const perCall = perCallScalars.length > 0 || unpinnedRandom; + if (!perCall) queue.writeBuffer(paramsBuffer, 0, mirror); + const entries = [ { + binding: 0, + resource: { + buffer: paramsBuffer + } + } ]; + for (let j = 0; j < argBuffers.length; j++) entries.push({ + binding: 1 + j, + resource: { + buffer: argBuffers[j] + } + }); + const outBinding = 1 + argBuffers.length; + entries.push({ + binding: outBinding, + resource: { + buffer: outputBuffer + } + }); + for (let j = 0; j < layout.bufferConstants.length; j++) entries.push({ + binding: outBinding + 1 + j, + resource: { + buffer: layout.bufferConstants[j].buffer + } + }); + stepPass = { + pipeline: kernel.computePipeline, + bindGroup: device.createBindGroup({ + layout: kernel.bindGroupLayout, + entries: entries + }), + groups: dispatch.groups, + paramsBuffer: paramsBuffer, + mirror: mirror, + u32: u32, + i32: i32, + f32: f32, + perCall: perCall, + perCallScalars: perCallScalars, + seedOffset: unpinnedRandom ? layout.randomSeedOffset : null + }; + this._paramsRecords.push(stepPass); + passRecords.set(key, stepPass); + } + this._passes[i] = stepPass; + } + let stagingBytes = 0; + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === "step") { + const step = plan.steps[binding.step]; + const planBuffer = this._planBuffers[step.outputBuffer]; + const kernel = stepPrograms[binding.step].kernel; + const byteLength = planBuffer.cells * kernel.componentCount * 4; + const read = { + kind: "step", + buffer: planBuffer.buffer, + offset: stagingBytes, + byteLength: byteLength, + output: step.output, + componentCount: kernel.componentCount, + kernel: kernel + }; + stagingBytes += align16(byteLength); + return read; + } + if (binding.source === "pipelineArg") return { + kind: "arg", + index: binding.index + }; + return { + kind: "literal", + value: binding.value + }; + }); + if (stagingBytes > 0) this._staging = device.createBuffer({ + size: stagingBytes, + usage: 9 + }); + } + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === "pipelineArg") reps[j] = args[binding.index]; else if (binding.source === "literal") reps[j] = binding.value; else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + async _prepareKernel(kernel, reps) { + if (kernel.built || kernel._buildPromise) { + const gpuKernels = kernel.gpu && kernel.gpu.kernels; + kernel.destroy(); + if (gpuKernels && gpuKernels.indexOf(kernel) === -1) gpuKernels.push(kernel); + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; + } + await kernel.build.apply(kernel, reps); + if (kernel.outputBuffer) { + if (--kernel.outputBuffer._refs === 0) kernel.outputBuffer.destroy(); + kernel.outputBuffer = null; + } + } + _checkArguments(args) { + for (const [index, region] of this._argRegions) { + const value = args[index]; + if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + if (isResidentHandle(value)) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); + } + for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + } + _writeScalar(u32, i32, f32, record, value) { + const slot = record.offset / 4; + if (record.type === "Integer") i32[slot] = value | 0; else if (record.type === "Boolean") u32[slot] = value ? 1 : 0; else f32[slot] = value; + } + execute(args) { + if (this.destroyed) throw new Error("pipeline fused executor has been destroyed"); + if (this.context && this.context.isLost) return Promise.reject(new Error("WebGPU device was lost; the pipeline will rebuild on a fresh device on its next call")); + this._checkArguments(args); + const device = this._device; + const queue = device.queue; + for (const [index, region] of this._argRegions) { + const value = args[index]; + utils.flattenTo(value instanceof Input ? value.value : value, region.scratch); + queue.writeBuffer(region.buffer, 0, region.scratch); + } + for (let i = 0; i < this._paramsRecords.length; i++) { + const record = this._paramsRecords[i]; + if (!record.perCall) continue; + for (let j = 0; j < record.perCallScalars.length; j++) { + const slot = record.perCallScalars[j]; + this._writeScalar(record.u32, record.i32, record.f32, slot, args[slot.index]); + } + if (record.seedOffset !== null) record.u32[record.seedOffset / 4] = Math.random() * 4294967296 >>> 0; + queue.writeBuffer(record.paramsBuffer, 0, record.mirror); + } + const encoder = device.createCommandEncoder(); + for (let i = 0; i < this._passes.length; i++) { + const stepPass = this._passes[i]; + const pass = encoder.beginComputePass(); + pass.setPipeline(stepPass.pipeline); + pass.setBindGroup(0, stepPass.bindGroup); + pass.dispatchWorkgroups(stepPass.groups[0], stepPass.groups[1], stepPass.groups[2]); + pass.end(); + } + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") encoder.copyBufferToBuffer(read.buffer, 0, this._staging, read.offset, read.byteLength); + } + queue.submit([ encoder.finish() ]); + if (!this._staging) return Promise.resolve(this._shapeResults(args, null)); + return this._staging.mapAsync(MAP_MODE_READ).then(() => { + const mapped = this._staging.getMappedRange(); + const values = this._shapeResults(args, mapped); + this._staging.unmap(); + return values; + }); + } + _shapeResults(args, mapped) { + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === "step") { + const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } + if (results.kind === "single") return values[0]; + if (results.kind === "array") return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) shaped[results.entries[i].key] = values[i]; + return shaped; + } + destroy() { + if (this.destroyed) return; + this.destroyed = true; + if (this._planBuffers) for (let i = 0; i < this._planBuffers.length; i++) this._planBuffers[i].buffer.destroy(); + for (const region of this._argRegions.values()) region.buffer.destroy(); + for (const literal of this._literalBuffers.values()) literal.buffer.destroy(); + for (let i = 0; i < this._paramsRecords.length; i++) this._paramsRecords[i].paramsBuffer.destroy(); + if (this._staging) { + this._staging.destroy(); + this._staging = null; + } + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) shortcut.destroy(); + } + this._extraShortcuts = []; + this._planBuffers = null; + this._argRegions = new Map; + this._argScalarSlots = new Map; + this._literalBuffers = new Map; + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + } + } + }; + }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; @@ -23979,6 +24438,7 @@ }; function snapshotValue(value, held) { if (!value || typeof value !== "object") return value; + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); if (typeof value.delete === "function" || typeof value.toArray === "function") { if (typeof value.clone === "function" && held) { const cloned = value.clone(); @@ -23989,7 +24449,6 @@ } if (ArrayBuffer.isView(value)) return value.slice(0); if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); - if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } function releaseSnapshots(held) { @@ -24094,22 +24553,22 @@ const sampled = new Array(args.length); const held = []; for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); - const promise = this._tail.then(() => { + const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { this.plan = this._buildPlan(); this._executor = void 0; } - if (this._executor === void 0) this._prepareExecutor(sampled); + if (this._executor === void 0) await this._prepareExecutor(sampled); if (this._executor) try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); if (e.recompilable) { - this._prepareExecutor(sampled); + await this._prepareExecutor(sampled); if (this._executor) try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -24194,8 +24653,19 @@ this._executor = false; return; } + const kernels = this.plan.kernels; + if (kernels.length > 0 && kernels[0].clone.kernel.constructor.mode === "webgpu") { + const {WebGPUPipelineExecutor: WebGPUPipelineExecutor} = require_pipeline_executor(); + return WebGPUPipelineExecutor.compile(this, this.plan, args).then(executor => { + this._executor = executor; + this.executorKind = executor.kind; + this.fallbackReason = null; + }, e => { + this._degrade(e && e.message || "fused executor unavailable"); + }); + } try { - const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor(); + const {WebAssemblyPipelineExecutor: WebAssemblyPipelineExecutor} = require_pipeline_executor$1(); this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); this.executorKind = this._executor.kind; this.fallbackReason = null; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index f6a2c1fd..4f3c7ebe 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:38:33 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var z=256;function B(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&z)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&z)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(B(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|B(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|B(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function ze(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Be(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ze(s=e.current());)e.lastIntValue=16*e.lastIntValue+Be(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;eB.needsArgumentType(e,t),k=(e,t,s)=>{B.assignArgumentType(e,t,s)},C=(e,t,s)=>B.lookupReturnType(e,t,s),L=e=>B.lookupFunctionArgumentTypes(e),D=(e,t)=>B.lookupFunctionArgumentName(e,t),F=(e,t)=>B.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{B.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{B.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{B.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let z=null;b&&(z=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const B=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:z});return B}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:z}=D(),{GLTextureUnsigned3D:B}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=B,null):this.output[1]>0?(this.TextureConstructor=z,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=B,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=z,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),z=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=z();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=B(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=B();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=ze();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=ze(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e instanceof s?new s(p(e.value,t),e.size):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(this._prepareExecutor(t),this._executor)try{return this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)this._executor=!1;else try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:s}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=mt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function u(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function l(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}u[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=d.get(e);return void 0===t&&(t=d.size,d.set(e,t)),t},m=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),v=null!==d.randomSeedOffset&&null===p.randomSeed,S=l.id+":"+g.map(f).join(",")+">"+f(x)+":"+b+(v?"#"+r:"");let T=m.get(S);if(!T){const e=new ArrayBuffer(d.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=p._computeDispatch(p.threadDim);t[0]=p.threadDim[0],t[1]=p.threadDim[1],t[2]=p.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:d.byteLength,usage:72}),l=o.length>0||v;l||c.writeBuffer(u,0,e);const f=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=u[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:g,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return g+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),g>0&&(this._staging=h.createBuffer({size:g,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/docs/design/pipeline-compilation.md b/docs/design/pipeline-compilation.md index 2f54a39c..978f8f81 100644 --- a/docs/design/pipeline-compilation.md +++ b/docs/design/pipeline-compilation.md @@ -79,10 +79,21 @@ const result = await solve(u0, q); // one launch, fences inside, one readback - `pipeline.destroy()` releases plan buffers/instances; gpu.destroy() reaches pipelines like kernels. +- webgpu fused executor ('fused-encoder', added after v1's generic-only + lowering): every plan step compiles against persistent STORAGE buffers on + the kernel's device — ping-pong as static alternating bind groups, per-step + params uniforms created at compile. Per call: pipeline arguments and + per-call seeds/scalars via queue.writeBuffer, EVERY step recorded as a + compute pass into ONE command encoder, result buffers copied to MAP_READ + staging in the same encoder, one queue.submit, one mapAsync readback. + Math.random keeps the direct-call seeding contract (seed uniform per call). + Anything unfusable (GPU-resident handle arguments, vec intermediates, + argument drift the layout cannot absorb) degrades to the generic executor + with a named fallbackReason. + ## v1 exclusions (documented, not silently missing) - No `this.check` / mid-plan readback (reserved; design in README as future). -- No webgpu single-command-encoder lowering (generic executor only; noted). - No graphical kernels inside pipelines (throw with message). - No kernel maps inside pipelines in v1 (throw with message). - `toString()` deferred. @@ -93,6 +104,7 @@ const result = await solve(u0, q); // one launch, fences inside, one readback - `src/gpu.js` — `createPipeline` wiring; pipeline registry for destroy. - `src/backend/web-assembly/pipeline-executor.js` — fused sync + threaded barrier lowering (worker-pool changes as needed). +- `src/backend/web-gpu/pipeline-executor.js` — the fused-encoder lowering. - `test/features/pipeline/*.js` — see testing section. - README section + `src/index.d.ts` declarations. diff --git a/src/backend/web-gpu/pipeline-executor.js b/src/backend/web-gpu/pipeline-executor.js new file mode 100644 index 00000000..b688130a --- /dev/null +++ b/src/backend/web-gpu/pipeline-executor.js @@ -0,0 +1,609 @@ +const { utils } = require('../../utils'); +const { Input } = require('../../input'); +const { FusionFallback } = require('../web-assembly/pipeline-executor'); + +/** + * Fused pipeline execution for webgpu (docs/design/pipeline-compilation.md): + * every plan step builds through the kernel's own WGSL machinery and then + * runs against persistent storage buffers — plan buffers allocated once on + * the shared device, ping-pong steps landing on static alternating bind + * groups, per-step params uniforms created at compile. A call writes the + * pipeline arguments and any per-call params (scalar arguments, unpinned + * random seeds), records EVERY step as a compute pass into ONE command + * encoder, copies the result buffers into a single staging buffer inside + * that same encoder, submits once, and resolves through one mapAsync + * readback. + */ + +// GPUBufferUsage/GPUMapMode are globals only where WebGPU exists; the +// numeric values are pinned by the spec (same convention as kernel.js) +const USAGE_UNIFORM = 0x0040; +const USAGE_STORAGE = 0x0080; +const USAGE_COPY_SRC = 0x0004; +const USAGE_COPY_DST = 0x0008; +const USAGE_MAP_READ = 0x0001; +const MAP_MODE_READ = 0x0001; + +function valueDimensions(value) { + const dims = value instanceof Input ? + Array.from(value.size) : + Array.from(utils.getDimensions(value)); + while (dims.length < 3) { + dims.push(1); + } + return dims; +} + +function scalarMatches(type, value) { + switch (type) { + case 'Integer': + return typeof value === 'number' && Number.isInteger(value); + case 'Boolean': + return typeof value === 'boolean'; + default: + return typeof value === 'number'; + } +} + +// Input also has a toArray(); only texture/buffer handles are resident +function isResidentHandle(value) { + return Boolean(value) && typeof value === 'object' && !(value instanceof Input) && + (typeof value.toArray === 'function' || typeof value.delete === 'function'); +} + +function align16(value) { + return Math.ceil(value / 16) * 16; +} + +class WebGPUPipelineExecutor { + /** + * @param {Pipeline} pipeline + * @param {Object} plan - the plan IR; buffer assignment is reused as-is + * @param {Array} args - the first call's sampled arguments; their sizes and + * types bake into the layout, and execute() re-checks them per call + * @returns {Promise} + * @throws {FusionFallback} for anything the encoder cannot take statically + */ + static async compile(pipeline, plan, args) { + for (let i = 0; i < plan.kernels.length; i++) { + const kernel = plan.kernels[i].clone.kernel; + if (kernel.constructor.mode !== 'webgpu') { + throw new FusionFallback(`pipeline backend is ${ kernel.constructor.mode }; the fused encoder requires webgpu`); + } + } + if (plan.steps.length === 0) { + throw new FusionFallback('plan has no kernel steps to fuse'); + } + const executor = new WebGPUPipelineExecutor(pipeline, plan); + try { + await executor._compile(args); + } catch (e) { + executor.destroy(); + throw e; + } + return executor; + } + + constructor(pipeline, plan) { + this.pipeline = pipeline; + this.gpu = pipeline.gpu; + this.plan = plan; + this.kind = 'fused-encoder'; + this.destroyed = false; + this.context = null; + this._device = null; + this._planBuffers = null; + this._argRegions = new Map(); + this._argScalarSlots = new Map(); + this._literalBuffers = new Map(); + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + this._staging = null; + /** + * kernels created for second and later type signatures of one plan + * kernel (the plan clone carries the first); destroyed with the executor + */ + this._extraShortcuts = []; + // representative Float32Arrays for step-output bindings, keyed by flat + // length; compile-time only, released when _compile returns + this._scratch = new Map(); + } + + async _compile(args) { + const plan = this.plan; + // a GPU-resident handle argument cannot bind statically — a different + // buffer arrives every call; the generic executor takes handles natively + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === 'pipelineArg' && isResidentHandle(args[binding.index])) { + throw new FusionFallback(`pipeline argument ${ binding.index } is a GPU-resident handle; the fused encoder takes plain arrays`); + } + } + } + // a program is a plan kernel built for one argument-type signature: the + // kernel's own build() ran (WGSL, compute pipeline, constant buffers), + // but its run() never will — the executor encodes the passes itself + const programs = new Map(); + const cloneClaimed = new Array(plan.kernels.length).fill(false); + const stepPrograms = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const kernelEntry = plan.kernels[step.kernel]; + const reps = this._representativeArgs(step, args); + const strict = kernelEntry.clone.kernel.strictIntegers; + const programKey = step.kernel + ':' + reps.map(value => utils.getVariableType(value, strict)).join(','); + let program = programs.get(programKey); + if (!program) { + let kernel; + if (!cloneClaimed[step.kernel]) { + cloneClaimed[step.kernel] = true; + kernel = kernelEntry.clone.kernel; + } else { + // from the plan's frozen clone, NOT the live user kernel: a + // setOutput between trace and recompile must not bake the user's + // current shape over the plan's trace-time one + const extra = this.pipeline._cloneKernel(kernelEntry.clone); + this._extraShortcuts.push(extra); + kernel = extra.kernel; + } + await this._prepareKernel(kernel, reps); + program = { id: programs.size, kernel }; + programs.set(programKey, program); + } + stepPrograms[i] = program; + } + this._scratch = null; + // vec-returning steps pack componentCount values per cell; the flat + // array accessors read stride 1, so only results may consume them + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source === 'step' && stepPrograms[binding.step].kernel.componentCount !== 1) { + throw new FusionFallback(`a step returning ${ stepPrograms[binding.step].kernel.returnType } cannot feed another step in the fused encoder`); + } + } + } + + const device = this._device = stepPrograms[0].kernel._device; + this.context = stepPrograms[0].kernel.context; + const queue = device.queue; + + const bufferComponents = new Array(plan.buffers.length).fill(1); + for (let i = 0; i < plan.steps.length; i++) { + const b = plan.steps[i].outputBuffer; + bufferComponents[b] = Math.max(bufferComponents[b], stepPrograms[i].kernel.componentCount); + } + this._planBuffers = plan.buffers.map((record, b) => { + const dims = record.output; + let cells = 1; + for (let d = 0; d < dims.length; d++) cells *= dims[d]; + return { + cells, + buffer: device.createBuffer({ + size: cells * bufferComponents[b] * 4, + usage: USAGE_STORAGE | USAGE_COPY_SRC, + }), + }; + }); + + // one pass record per distinct (program, buffer assignment, baked + // scalars): the ping-pong loop lands on two records with static bind + // groups however many steps it unrolled to + const bufferIds = new Map(); + const idOf = buffer => { + let id = bufferIds.get(buffer); + if (id === undefined) { + id = bufferIds.size; + bufferIds.set(buffer, id); + } + return id; + }; + const passRecords = new Map(); + this._passes = new Array(plan.steps.length); + for (let i = 0; i < plan.steps.length; i++) { + const step = plan.steps[i]; + const program = stepPrograms[i]; + const kernel = program.kernel; + const layout = kernel.paramsLayout; + const argBuffers = new Array(layout.arrayArgs.length); + const argDims = new Array(layout.arrayArgs.length); + for (let j = 0; j < layout.arrayArgs.length; j++) { + const record = layout.arrayArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === 'pipelineArg') { + let region = this._argRegions.get(binding.index); + if (!region) { + const dims = valueDimensions(args[binding.index]); + const flatLength = dims[0] * dims[1] * dims[2]; + region = { + dims, + flatLength, + scratch: new Float32Array(flatLength), + buffer: device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: USAGE_STORAGE | USAGE_COPY_DST, + }), + }; + this._argRegions.set(binding.index, region); + } + argBuffers[j] = region.buffer; + argDims[j] = region.dims; + } else if (binding.source === 'literal') { + let literal = this._literalBuffers.get(binding.value); + if (!literal) { + const dims = valueDimensions(binding.value); + const flatLength = dims[0] * dims[1] * dims[2]; + const buffer = device.createBuffer({ + size: Math.max(flatLength * 4, 4), + usage: USAGE_STORAGE, + mappedAtCreation: true, + }); + const mapped = new Float32Array(buffer.getMappedRange()); + utils.flattenTo(binding.value instanceof Input ? binding.value.value : binding.value, mapped.subarray(0, flatLength)); + buffer.unmap(); + literal = { buffer, dims }; + this._literalBuffers.set(binding.value, literal); + } + argBuffers[j] = literal.buffer; + argDims[j] = literal.dims; + } else { + const producer = plan.steps[binding.step]; + const dims = Array.from(producer.output); + while (dims.length < 3) dims.push(1); + argBuffers[j] = this._planBuffers[producer.outputBuffer].buffer; + argDims[j] = dims; + } + } + const outputBuffer = this._planBuffers[step.outputBuffer].buffer; + // baked scalar values are part of the pass identity: two steps can + // share every buffer yet differ in a literal scalar + const scalarSignature = layout.scalarArgs.map(record => { + const binding = step.argBindings[record.index]; + return binding.source === 'literal' ? 'l' + binding.value : 'a' + binding.index; + }).join(','); + // an unpinned kernel draws per call AND per step, matching the generic + // executor's one draw per kernel run; a pinned seed is baked, so + // ping-pong steps may share their params + const unpinnedRandom = layout.randomSeedOffset !== null && kernel.randomSeed === null; + const key = program.id + ':' + argBuffers.map(idOf).join(',') + '>' + idOf(outputBuffer) + + ':' + scalarSignature + (unpinnedRandom ? '#' + i : ''); + let stepPass = passRecords.get(key); + if (!stepPass) { + const mirror = new ArrayBuffer(layout.byteLength); + const u32 = new Uint32Array(mirror); + const i32 = new Int32Array(mirror); + const f32 = new Float32Array(mirror); + const dispatch = kernel._computeDispatch(kernel.threadDim); + u32[0] = kernel.threadDim[0]; + u32[1] = kernel.threadDim[1]; + u32[2] = kernel.threadDim[2]; + u32[3] = dispatch.dispatchWidth; + for (let j = 0; j < layout.arrayArgs.length; j++) { + const base = layout.arrayArgs[j].dimsOffset / 4; + u32[base] = argDims[j][0]; + u32[base + 1] = argDims[j][1]; + u32[base + 2] = argDims[j][2]; + u32[base + 3] = argDims[j][0] * argDims[j][1] * argDims[j][2]; + } + const perCallScalars = []; + for (let j = 0; j < layout.scalarArgs.length; j++) { + const record = layout.scalarArgs[j]; + const binding = step.argBindings[record.index]; + if (binding.source === 'literal') { + this._writeScalar(u32, i32, f32, record, binding.value); + } else if (binding.source === 'pipelineArg') { + perCallScalars.push({ index: binding.index, offset: record.offset, type: record.type }); + this._argScalarSlots.set(binding.index + ':' + record.type, { index: binding.index, type: record.type }); + } else { + // unreachable by construction: step-output reps are Inputs, so + // inference can never type this position scalar + throw new FusionFallback('a step output cannot bind to a scalar argument'); + } + } + if (layout.randomSeedOffset !== null && kernel.randomSeed !== null) { + u32[layout.randomSeedOffset / 4] = kernel.randomSeed >>> 0; + } + const paramsBuffer = device.createBuffer({ + size: layout.byteLength, + usage: USAGE_UNIFORM | USAGE_COPY_DST, + }); + const perCall = perCallScalars.length > 0 || unpinnedRandom; + if (!perCall) { + // everything in this params struct is baked; upload exactly once + queue.writeBuffer(paramsBuffer, 0, mirror); + } + const entries = [{ binding: 0, resource: { buffer: paramsBuffer } }]; + for (let j = 0; j < argBuffers.length; j++) { + entries.push({ binding: 1 + j, resource: { buffer: argBuffers[j] } }); + } + const outBinding = 1 + argBuffers.length; + entries.push({ binding: outBinding, resource: { buffer: outputBuffer } }); + for (let j = 0; j < layout.bufferConstants.length; j++) { + entries.push({ binding: outBinding + 1 + j, resource: { buffer: layout.bufferConstants[j].buffer } }); + } + stepPass = { + pipeline: kernel.computePipeline, + bindGroup: device.createBindGroup({ layout: kernel.bindGroupLayout, entries }), + groups: dispatch.groups, + paramsBuffer, + mirror, + u32, + i32, + f32, + perCall, + perCallScalars, + seedOffset: unpinnedRandom ? layout.randomSeedOffset : null, + }; + this._paramsRecords.push(stepPass); + passRecords.set(key, stepPass); + } + this._passes[i] = stepPass; + } + + let stagingBytes = 0; + this._resultReads = plan.results.entries.map(entry => { + const binding = entry.binding; + if (binding.source === 'step') { + const step = plan.steps[binding.step]; + const planBuffer = this._planBuffers[step.outputBuffer]; + const kernel = stepPrograms[binding.step].kernel; + const byteLength = planBuffer.cells * kernel.componentCount * 4; + const read = { + kind: 'step', + buffer: planBuffer.buffer, + offset: stagingBytes, + byteLength, + output: step.output, + componentCount: kernel.componentCount, + kernel, + }; + stagingBytes += align16(byteLength); + return read; + } + if (binding.source === 'pipelineArg') { + return { kind: 'arg', index: binding.index }; + } + return { kind: 'literal', value: binding.value }; + }); + if (stagingBytes > 0) { + this._staging = device.createBuffer({ + size: stagingBytes, + usage: USAGE_MAP_READ | USAGE_COPY_DST, + }); + } + } + + /** + * Stand-ins with the exact types and dims each binding will have at run + * time, for the kernel build: sampled values stand for themselves, a step + * output becomes an Input over its producer's dims. + */ + _representativeArgs(step, args) { + const reps = new Array(step.argBindings.length); + for (let j = 0; j < step.argBindings.length; j++) { + const binding = step.argBindings[j]; + if (binding.source === 'pipelineArg') { + reps[j] = args[binding.index]; + } else if (binding.source === 'literal') { + reps[j] = binding.value; + } else { + const output = this.plan.steps[binding.step].output; + let flatLength = 1; + for (let d = 0; d < output.length; d++) flatLength *= output[d]; + let scratch = this._scratch.get(flatLength); + if (!scratch) { + scratch = new Float32Array(flatLength); + this._scratch.set(flatLength, scratch); + } + reps[j] = new Input(scratch, Array.from(output)); + } + } + return reps; + } + + /** + * The kernel's own build() carries the whole WGSL path — inference, + * translation, compute-pipeline creation, constant upload; the executor + * reuses its computePipeline/bindGroupLayout/paramsLayout and never calls + * run(). On a recompile after argument drift the clone is already built, + * so the previous device objects are released and inference reset first. + */ + async _prepareKernel(kernel, reps) { + if (kernel.built || kernel._buildPromise) { + // destroy() unregisters the clone; the plan-release guard needs it + // back in gpu.kernels + const gpuKernels = kernel.gpu && kernel.gpu.kernels; + kernel.destroy(); + if (gpuKernels && gpuKernels.indexOf(kernel) === -1) { + gpuKernels.push(kernel); + } + kernel.argumentTypes = kernel.declaredArgumentTypes ? kernel.declaredArgumentTypes.slice() : null; + } + await kernel.build.apply(kernel, reps); + // every step writes a plan buffer; the output buffer the build allocated + // would only hold memory + if (kernel.outputBuffer) { + if (--kernel.outputBuffer._refs === 0) { + kernel.outputBuffer.destroy(); + } + kernel.outputBuffer = null; + } + } + + /** + * The layout baked argument sizes and scalar types; a call that drifts + * from them throws recompilable so the pipeline compiles a fresh fused + * plan for the new signature, the way the kernel itself rebuilds per size + * signature. + */ + _checkArguments(args) { + for (const [index, region] of this._argRegions) { + const value = args[index]; + if (!value || typeof value !== 'object') { + throw new FusionFallback(`pipeline argument ${ index } is no longer an array`, true); + } + if (isResidentHandle(value)) { + // the recompile declines handles with its own named reason and the + // pipeline degrades to the generic executor from there + throw new FusionFallback(`pipeline argument ${ index } is now a GPU-resident handle`, true); + } + const dims = valueDimensions(value); + if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) { + throw new FusionFallback(`pipeline argument ${ index } changed size from [${ region.dims.join(', ') }] to [${ dims.join(', ') }]`, true); + } + } + for (const slot of this._argScalarSlots.values()) { + if (!scalarMatches(slot.type, args[slot.index])) { + throw new FusionFallback(`pipeline argument ${ slot.index } is no longer of type ${ slot.type }`, true); + } + } + } + + _writeScalar(u32, i32, f32, record, value) { + const slot = record.offset / 4; + if (record.type === 'Integer') { + i32[slot] = value | 0; + } else if (record.type === 'Boolean') { + u32[slot] = value ? 1 : 0; + } else { + f32[slot] = value; + } + } + + /** + * @param {Array} args - sampled pipeline arguments + * @returns {Promise<*>} results shaped per the plan. Argument drift throws + * a recompilable FusionFallback synchronously, before anything is encoded; + * async failures (device loss) reject, which drops the executor via the + * pipeline's _guardAsync so the next call compiles fresh. + */ + execute(args) { + if (this.destroyed) { + throw new Error('pipeline fused executor has been destroyed'); + } + if (this.context && this.context.isLost) { + // reject rather than throw: the rejection path drops this executor, + // and the recompile re-acquires a fresh device + return Promise.reject(new Error('WebGPU device was lost; the pipeline will rebuild on a fresh device on its next call')); + } + this._checkArguments(args); + const device = this._device; + const queue = device.queue; + for (const [index, region] of this._argRegions) { + const value = args[index]; + utils.flattenTo(value instanceof Input ? value.value : value, region.scratch); + queue.writeBuffer(region.buffer, 0, region.scratch); + } + for (let i = 0; i < this._paramsRecords.length; i++) { + const record = this._paramsRecords[i]; + if (!record.perCall) continue; + for (let j = 0; j < record.perCallScalars.length; j++) { + const slot = record.perCallScalars[j]; + this._writeScalar(record.u32, record.i32, record.f32, slot, args[slot.index]); + } + if (record.seedOffset !== null) { + record.u32[record.seedOffset / 4] = (Math.random() * 0x100000000) >>> 0; + } + queue.writeBuffer(record.paramsBuffer, 0, record.mirror); + } + const encoder = device.createCommandEncoder(); + for (let i = 0; i < this._passes.length; i++) { + const stepPass = this._passes[i]; + const pass = encoder.beginComputePass(); + pass.setPipeline(stepPass.pipeline); + pass.setBindGroup(0, stepPass.bindGroup); + pass.dispatchWorkgroups(stepPass.groups[0], stepPass.groups[1], stepPass.groups[2]); + pass.end(); + } + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === 'step') { + encoder.copyBufferToBuffer(read.buffer, 0, this._staging, read.offset, read.byteLength); + } + } + queue.submit([encoder.finish()]); + if (!this._staging) { + return Promise.resolve(this._shapeResults(args, null)); + } + // calls serialize on the pipeline tail, so the single staging buffer is + // never mapped twice at once + return this._staging.mapAsync(MAP_MODE_READ).then(() => { + const mapped = this._staging.getMappedRange(); + const values = this._shapeResults(args, mapped); + this._staging.unmap(); + return values; + }); + } + + _shapeResults(args, mapped) { + const results = this.plan.results; + const values = new Array(this._resultReads.length); + for (let i = 0; i < this._resultReads.length; i++) { + const read = this._resultReads[i]; + if (read.kind === 'step') { + const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); + values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); + } else if (read.kind === 'arg') { + values[i] = args[read.index]; + } else { + values[i] = read.value; + } + } + if (results.kind === 'single') return values[0]; + if (results.kind === 'array') return values; + const shaped = {}; + for (let i = 0; i < values.length; i++) { + shaped[results.entries[i].key] = values[i]; + } + return shaped; + } + + destroy() { + if (this.destroyed) return; + this.destroyed = true; + // destroying buffers on a lost/destroyed device is legal per spec + if (this._planBuffers) { + for (let i = 0; i < this._planBuffers.length; i++) { + this._planBuffers[i].buffer.destroy(); + } + } + for (const region of this._argRegions.values()) { + region.buffer.destroy(); + } + for (const literal of this._literalBuffers.values()) { + literal.buffer.destroy(); + } + for (let i = 0; i < this._paramsRecords.length; i++) { + this._paramsRecords[i].paramsBuffer.destroy(); + } + if (this._staging) { + this._staging.destroy(); + this._staging = null; + } + const gpuKernels = this.gpu && this.gpu.kernels; + for (let i = 0; i < this._extraShortcuts.length; i++) { + const shortcut = this._extraShortcuts[i]; + // same guard as Pipeline._releasePlan: gpu.destroy() may already have + // reached this kernel, and kernel destroy is not re-entrant + if (!gpuKernels || gpuKernels.indexOf(shortcut.kernel) !== -1) { + shortcut.destroy(); + } + } + this._extraShortcuts = []; + this._planBuffers = null; + this._argRegions = new Map(); + this._argScalarSlots = new Map(); + this._literalBuffers = new Map(); + this._paramsRecords = []; + this._passes = null; + this._resultReads = null; + } +} + +module.exports = { + WebGPUPipelineExecutor, +}; \ No newline at end of file diff --git a/src/index.d.ts b/src/index.d.ts index 52f2c719..8b419268 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -437,7 +437,8 @@ export interface IPipelineRunShortcut { * 'generic' runs step-by-step through the normal kernel machinery on every * backend; 'fused-sync' runs every step over one shared wasm memory on the * webasm backend; 'fused-threaded' has pool workers walk the whole plan - * over that memory on an Atomics barrier + * over that memory on an Atomics barrier; 'fused-encoder' records every + * step into one WebGPU command encoder over persistent storage buffers */ readonly executorKind: string; /** why the fused executor declined this plan; null while fused */ diff --git a/src/pipeline.js b/src/pipeline.js index 39878e21..5041a2b0 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -163,6 +163,8 @@ class PipelineTrace { */ function snapshotValue(value, held) { if (!value || typeof value !== 'object') return value; + // before the texture duck-type check: Input also has a toArray() + if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); if (typeof value.delete === 'function' || typeof value.toArray === 'function') { // a mutable (immutable: false) texture is re-rendered IN PLACE by its // kernel's next call, so passing it through uncopied would sample the @@ -177,7 +179,6 @@ function snapshotValue(value, held) { } if (ArrayBuffer.isView(value)) return value.slice(0); if (Array.isArray(value)) return value.map(v => snapshotValue(v, held)); - if (value instanceof Input) return new Input(snapshotValue(value.value, held), value.size); return value; } @@ -314,7 +315,9 @@ class Pipeline { * step-by-step through the normal kernel machinery on every backend; * 'fused-sync' is the webasm executor running every step over one shared * wasm memory; 'fused-threaded' is that executor with pool workers - * walking the whole plan on an Atomics barrier + * walking the whole plan on an Atomics barrier; 'fused-encoder' is the + * webgpu executor recording every step into one command encoder over + * persistent storage buffers * @type {String} */ this.executorKind = 'generic'; @@ -354,28 +357,30 @@ class Pipeline { for (let i = 0; i < args.length; i++) { sampled[i] = snapshotValue(args[i], held); } - const promise = this._tail.then(() => { + const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { this.plan = this._buildPlan(); this._executor = undefined; } if (this._executor === undefined) { - this._prepareExecutor(sampled); + // synchronous for webasm; a promise for the webgpu encoder, whose + // compile awaits the device + await this._prepareExecutor(sampled); } if (this._executor) { try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e) { if (!e || !e.isFusionFallback) throw e; this._dropExecutor(); if (e.recompilable) { // argument sizes/types drifted: recompile fused for the new // signature, like the kernel's own per-size-signature rebuild - this._prepareExecutor(sampled); + await this._prepareExecutor(sampled); if (this._executor) { try { - return this._guardAsync(this._executor.execute(sampled)); + return await this._guardAsync(this._executor.execute(sampled)); } catch (e2) { if (!e2 || !e2.isFusionFallback) throw e2; this._dropExecutor(); @@ -504,18 +509,31 @@ class Pipeline { } /** - * Attempts the webasm fused executor for the current plan against this - * call's sampled arguments. Anything the webasm backend cannot take — - * including a non-webasm backend — degrades to the generic executor with - * the reason recorded, its usual degradation contract. + * Attempts the backend's fused executor for the current plan against this + * call's sampled arguments: the single-encoder lowering on webgpu (async — + * kernel builds await the device), the wasm-memory lowering everywhere + * else. Anything the fused compile cannot take degrades to the generic + * executor with the reason recorded, its usual degradation contract. * @param {Array} args - sampled pipeline arguments; sizes/types bake into * the fused layout + * @returns {Promise|undefined} */ _prepareExecutor(args) { if (this._fusionDisabled) { this._executor = false; return; } + const kernels = this.plan.kernels; + if (kernels.length > 0 && kernels[0].clone.kernel.constructor.mode === 'webgpu') { + const { WebGPUPipelineExecutor } = require('./backend/web-gpu/pipeline-executor'); + return WebGPUPipelineExecutor.compile(this, this.plan, args).then(executor => { + this._executor = executor; + this.executorKind = executor.kind; + this.fallbackReason = null; + }, e => { + this._degrade((e && e.message) || 'fused executor unavailable'); + }); + } try { const { WebAssemblyPipelineExecutor } = require('./backend/web-assembly/pipeline-executor'); this._executor = WebAssemblyPipelineExecutor.compile(this, this.plan, args); diff --git a/test/all.html b/test/all.html index 35998a5f..aa7c2620 100644 --- a/test/all.html +++ b/test/all.html @@ -310,6 +310,7 @@ + diff --git a/test/features/pipeline/correctness.js b/test/features/pipeline/correctness.js index a8513066..04316114 100644 --- a/test/features/pipeline/correctness.js +++ b/test/features/pipeline/correctness.js @@ -8,8 +8,9 @@ describe('features: pipeline correctness'); // browser with an adapter). executorKind is asserted per mode: webasm // compiles these plans to the fused executor, and a forced-generic webasm // variant keeps the correctness-reference executor covered on that backend -// too. webgpu has no fused lowering in v1, so its rows pin the generic -// executor over buffer-handle intermediates. +// too. webgpu rows force the generic executor so the correctness reference +// stays covered over buffer-handle intermediates; the fused-encoder lowering +// has its own suite in fused-webgpu.js. function assertClose(assert, actual, expected, label) { const values = Array.from(actual); @@ -214,8 +215,8 @@ eachMode('2d output kernels', async (assert, mode, kind) => { }); // the rows above force the generic executor; this one leaves fusion enabled -// so the webasm-only fused compile must decline webgpu by itself -(GPU.isWebGPUSupported ? test : skip)('webgpu degrades naturally to the generic executor', async assert => { +// so executor selection must land webgpu on its own fused encoder +(GPU.isWebGPUSupported ? test : skip)('webgpu compiles the fused encoder when fusion is left enabled', async assert => { if (!(await webgpuAdapter(assert))) return; const gpu = new GPU({ mode: 'webgpu' }); const double = gpu.createKernel(function (a) { @@ -225,8 +226,8 @@ eachMode('2d output kernels', async (assert, mode, kind) => { return double(double(x)); }); const result = await solve([1, 2, 3, 4]); - assert.equal(solve.executorKind, 'generic', 'no fused lowering for webgpu in v1'); - assert.ok(/webgpu/.test(solve.fallbackReason), `fallbackReason names the backend: ${ solve.fallbackReason }`); - assertClose(assert, result, [4, 8, 12, 16], 'degraded run is still correct'); + assert.equal(solve.executorKind, 'fused-encoder', 'webgpu plans compile to the single-encoder executor'); + assert.equal(solve.fallbackReason, null, 'no fallback reason while fused'); + assertClose(assert, result, [4, 8, 12, 16], 'fused run is correct'); await gpu.destroy(); }); diff --git a/test/features/pipeline/fused-webgpu.js b/test/features/pipeline/fused-webgpu.js new file mode 100644 index 00000000..c09ed48b --- /dev/null +++ b/test/features/pipeline/fused-webgpu.js @@ -0,0 +1,411 @@ +const { assert, skip, test, module: describe } = require('qunit'); +const { GPU } = require('../../../src'); + +describe('features: pipeline fused webgpu encoder'); + +// The fused-encoder executor records every plan step as a compute pass into +// ONE command encoder over persistent storage buffers; each scenario here +// asserts executorKind === 'fused-encoder' so a silent fall back to the +// generic executor fails the suite, and results are checked against the same +// pipeline forced onto the cpu backend. + +function assertClose(assert, actual, expected, label) { + const values = Array.from(actual); + assert.equal(values.length, expected.length, `${ label }: length`); + for (let i = 0; i < values.length; i++) { + const delta = Math.abs(values[i] - expected[i]); + const scale = Math.max(Math.abs(expected[i]), 1); + assert.ok(delta / scale <= 1e-5, `${ label } cell ${ i }: ${ values[i] } vs ${ expected[i] }`); + } +} + +// navigator.gpu can be present with no adapter (headless Chromium, blocklisted +// GPUs); QUnit cannot skip at runtime, so an adapterless environment records a +// pass with an explicit message and bumps a counter the headed canary rejects. +let adapterPromise = null; +async function webgpuAdapter(assert) { + if (!adapterPromise) adapterPromise = navigator.gpu.requestAdapter(); + const adapter = await adapterPromise; + if (!adapter) { + if (typeof window !== 'undefined') { + window.__webgpuRuntimeSkips = (window.__webgpuRuntimeSkips || 0) + 1; + } + assert.ok(true, 'navigator.gpu present but no adapter (headless/blocklisted) — runtime skip'); + } + return adapter; +} + +function webgpuTest(name, body) { + (GPU.isWebGPUSupported ? test : skip)(name, async assert => { + if (!(await webgpuAdapter(assert))) return; + return body(assert); + }); +} + +/** + * Builds the same kernels + pipeline on webgpu and on cpu, runs both with + * the same arguments, asserts the webgpu one compiled the fused encoder and + * answers match the cpu reference. + */ +async function fusedVsCpu(assert, makePipeline, argsList, compare) { + const webgpu = new GPU({ mode: 'webgpu' }); + const cpu = new GPU({ mode: 'cpu' }); + const fusedPipeline = makePipeline(webgpu); + const referencePipeline = makePipeline(cpu); + for (let i = 0; i < argsList.length; i++) { + const fused = await fusedPipeline.apply(null, argsList[i]); + const reference = await referencePipeline.apply(null, argsList[i]); + compare(fused, reference, `call ${ i }`); + } + assert.equal(fusedPipeline.executorKind, 'fused-encoder', 'webgpu compiled the fused encoder'); + assert.equal(fusedPipeline.fallbackReason, null, 'no fallback reason while fused'); + assert.equal(referencePipeline.executorKind, 'generic', 'cpu stays generic'); + await webgpu.destroy(); + cpu.destroy(); +} + +webgpuTest('jacobi ping-pong: one kernel, two static bind groups, args re-sampled per call', async assert => { + await fusedVsCpu(assert, gpu => { + const sweep = gpu.createKernel(function (u, q) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + let right = this.thread.x + 1; + if (right > 7) right = 7; + return 0.25 * (u[left] + u[right]) + q[this.thread.x]; + }, { output: [8] }); + return gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 7 } }); + }, [ + [[0, 1, 2, 3, 4, 5, 6, 7], [1, 0.5, 1, 0.5, 1, 0.5, 1, 0.5]], + // second call: different values through the SAME compiled layout + [[7, 6, 5, 4, 3, 2, 1, 0], [0.5, 1, 0.5, 1, 0.5, 1, 0.5, 1]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +webgpuTest('multi-kernel chain with double-buffer liveness (step 3 reads step 1)', async assert => { + await fusedVsCpu(assert, gpu => { + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const dbl = gpu.createKernel(function (u) { + return u[this.thread.x] * 2; + }, { output: [4] }); + const mix = gpu.createKernel(function (a, b) { + return a[this.thread.x] * 100 + b[this.thread.x]; + }, { output: [4] }); + return gpu.createPipeline(function (u) { + const a = inc(u); + const b = dbl(a); + return mix(b, a); + }); + }, [ + [[1, 2, 3, 4]], + [[5, 0, -3, 2.5]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +webgpuTest('object and array returns, pipeline arg reused by several steps', async assert => { + await fusedVsCpu(assert, gpu => { + const add = gpu.createKernel(function (a, b) { + return a[this.thread.x] + b[this.thread.x]; + }, { output: [4] }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4] }); + return gpu.createPipeline(function (u, q) { + const a = add(u, q); + const b = add(a, q); + return { sum: add(b, q), doubledU: dbl(u), doubledQ: dbl(q) }; + }); + }, [ + [[1, 2, 3, 4], [10, 10, 10, 10]], + ], (fused, reference, label) => { + assertClose(assert, fused.sum, Array.from(reference.sum), `${ label } sum`); + assertClose(assert, fused.doubledU, Array.from(reference.doubledU), `${ label } doubled u`); + assertClose(assert, fused.doubledQ, Array.from(reference.doubledQ), `${ label } doubled q`); + }); +}); + +webgpuTest('literal scalars, captured arrays, and buffer constants', async assert => { + const captured = [10, 20, 30, 40]; + await fusedVsCpu(assert, gpu => { + const scale = gpu.createKernel(function (a, k) { + return a[this.thread.x] * k + this.constants.bias[this.thread.x]; + }, { output: [4], constants: { bias: [1, 2, 3, 4] } }); + const offset = gpu.createKernel(function (a, o) { + return a[this.thread.x] + o[this.thread.x]; + }, { output: [4] }); + return gpu.createPipeline(function (x) { + return offset(scale(x, 3), captured); + }); + }, [ + [[1, 2, 3, 4]], + [[0, -1, 5, 0.5]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +webgpuTest('2d output through the ping-pong loop', async assert => { + await fusedVsCpu(assert, gpu => { + const blur = gpu.createKernel(function (m) { + let left = this.thread.x - 1; + if (left < 0) left = 0; + return (m[this.thread.y][left] + m[this.thread.y][this.thread.x]) / 2 + 1; + }, { output: [7, 3] }); + return gpu.createPipeline(function (m) { + for (let i = 0; i < this.constants.passes; i++) { + m = blur(m); + } + return m; + }, { constants: { passes: 4 } }); + }, [ + [[ + [0, 1, 2, 3, 4, 5, 6], + [10, 11, 12, 13, 14, 15, 16], + [20, 21, 22, 23, 24, 25, 26], + ]], + ], (fused, reference, label) => { + assert.equal(fused.length, 3, `${ label }: 2d shape`); + for (let y = 0; y < 3; y++) { + assertClose(assert, fused[y], Array.from(reference[y]), `${ label } row ${ y }`); + } + }); +}); + +webgpuTest('scalar pipeline args ride the per-call params write', async assert => { + await fusedVsCpu(assert, gpu => { + const step = gpu.createKernel(function (a, k, flip) { + if (flip) { + return a[this.thread.x] - k; + } + return a[this.thread.x] + k; + }, { output: [4] }); + return gpu.createPipeline(function (x, k, flip) { + return step(step(x, k, flip), k, flip); + }); + }, [ + [[1, 2, 3, 4], 2.5, false], + [[1, 2, 3, 4], 2.5, true], + [[1, 2, 3, 4], -1.5, true], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +webgpuTest('Input pipeline argument fuses and samples at call time', async assert => { + const { input } = require('../../../src'); + await fusedVsCpu(assert, gpu => { + const grow = gpu.createKernel(function (m) { + return m[this.thread.y][this.thread.x] + 1; + }, { output: [3, 2] }); + return gpu.createPipeline(function (m) { + return grow(grow(m)); + }); + }, [ + [input(new Float32Array([0, 1, 2, 10, 11, 12]), [3, 2])], + ], (fused, reference, label) => { + for (let y = 0; y < 2; y++) { + assertClose(assert, fused[y], Array.from(reference[y]), `${ label } row ${ y }`); + } + }); + // Input contents must sample at the call, exactly like plain arrays + const gpu = new GPU({ mode: 'webgpu' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(x); + }); + const backing = new Float32Array([1, 2, 3]); + const pending = solve(input(backing, [3])); + backing[0] = 100; + assertClose(assert, await pending, [2, 4, 6], 'mutation after the call does not leak in'); + await gpu.destroy(); +}); + +webgpuTest('two identical steps keep distinct output buffers', async assert => { + // same program, same input buffer, same baked scalars — only the output + // buffer distinguishes the two passes, so a pass-record collision here + // leaves the second step's plan buffer unwritten + await fusedVsCpu(assert, gpu => { + const inc = gpu.createKernel(function (u) { + return u[this.thread.x] + 1; + }, { output: [4] }); + const mix = gpu.createKernel(function (a, b) { + return a[this.thread.x] * 100 + b[this.thread.x]; + }, { output: [4] }); + return gpu.createPipeline(function (x) { + const a = inc(x); + const b = inc(x); + return mix(a, b); + }); + }, [ + [[1, 2, 3, 4]], + ], (fused, reference, label) => assertClose(assert, fused, Array.from(reference), label)); +}); + +webgpuTest('seeded Math.random reproduces the direct-call streams exactly', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const settings = { output: [8], randomSeed: 1234 }; + const jitter = gpu.createKernel(function (a) { + return a[this.thread.x] + Math.random(); + }, settings); + const solve = gpu.createPipeline(function (x) { + return jitter(jitter(x)); + }); + const x = [1, 2, 3, 4, 5, 6, 7, 8]; + // the pinned seed makes every run's stream identical, so two direct calls + // compose to exactly what the fused two-step plan must produce + const directOnce = await jitter(x); + const directTwice = await jitter(Array.from(directOnce)); + const fused = await solve(x); + assert.equal(solve.executorKind, 'fused-encoder'); + assertClose(assert, fused, Array.from(directTwice), 'seeded pipeline vs composed direct calls'); + const again = await solve(x); + assertClose(assert, again, Array.from(fused), 'seeded pipeline repeats bit-for-bit'); + await gpu.destroy(); +}); + +webgpuTest('unpinned Math.random draws a fresh seed per call', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const jitter = gpu.createKernel(function (a) { + return a[this.thread.x] + Math.random(); + }, { output: [8] }); + const solve = gpu.createPipeline(function (x) { + return jitter(x); + }); + const x = [0, 0, 0, 0, 0, 0, 0, 0]; + const first = await solve(x); + const second = await solve(x); + assert.equal(solve.executorKind, 'fused-encoder'); + let differs = false; + for (let i = 0; i < first.length; i++) { + if (first[i] !== second[i]) differs = true; + } + assert.ok(differs, 'two calls draw different streams'); + await gpu.destroy(); +}); + +webgpuTest('argument size change recompiles the fused plan and stays fused', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const total = gpu.createKernel(function (a, n) { + let sum = 0; + for (let i = 0; i < n; i++) { + sum += a[i]; + } + return sum + this.thread.x; + }, { output: [4], dynamicArguments: true, loopMaxIterations: 64 }); + const solve = gpu.createPipeline(function (x, n) { + return total(x, n); + }); + const first = await solve([1, 2, 3, 4], 4); + assert.equal(solve.executorKind, 'fused-encoder'); + assertClose(assert, first, [10, 11, 12, 13], 'first size'); + const second = await solve([1, 2, 3, 4, 5, 6], 6); + assert.equal(solve.executorKind, 'fused-encoder', 'still fused after a size change'); + assert.equal(solve.fallbackReason, null); + assertClose(assert, second, [21, 22, 23, 24], 'second size'); + const third = await solve([2, 2, 2, 2], 4); + assertClose(assert, third, [8, 9, 10, 11], 'back to the first size'); + await gpu.destroy(); +}); + +webgpuTest('degradation: a buffer-handle pipeline argument falls back with a reason', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const producer = gpu.createKernel(function (a) { + return a[this.thread.x] * 10; + }, { output: [4], pipeline: true }); + const addOne = gpu.createKernel(function (t) { + return t[this.thread.x] + 1; + }, { output: [4] }); + const solve = gpu.createPipeline(function (t) { + return addOne(addOne(t)); + }); + const handle = await producer([1, 2, 3, 4]); + const result = await solve(handle); + assert.equal(solve.executorKind, 'generic', 'fell back to the generic executor'); + assert.ok(/GPU-resident handle/.test(solve.fallbackReason), `reason names the cause: ${ solve.fallbackReason }`); + assertClose(assert, result, [12, 22, 32, 42], 'generic executor still answers correctly'); + await gpu.destroy(); +}); + +webgpuTest('concurrent fused calls serialize and answer from their own arguments', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(dbl(x)); + }); + const buf = [1, 2, 3]; + const firstCall = solve(buf); + buf[0] = 100; // sampled at call time; must not leak into the first call + const secondCall = solve(buf); + const [first, second] = await Promise.all([firstCall, secondCall]); + assertClose(assert, first, [4, 8, 12], 'first call'); + assertClose(assert, second, [400, 8, 12], 'second call'); + assert.equal(solve.executorKind, 'fused-encoder'); + await gpu.destroy(); +}); + +webgpuTest('destroy releases the executor GPU buffers and later calls reject', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const sweep = gpu.createKernel(function (u, q) { + return u[this.thread.x] * 0.5 + q[this.thread.x]; + }, { output: [8] }); + const solve = gpu.createPipeline(function (u, q) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, q); + } + return u; + }, { constants: { sweeps: 4 } }); + await solve([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 1, 1, 1, 1, 1, 1]); + assert.equal(solve.executorKind, 'fused-encoder'); + // 2 plan buffers (ping-pong) + 2 argument regions + 2 params uniforms + + // 1 staging = 7 executor buffers, plus the released clone-kernel build + const originalDestroy = GPUBuffer.prototype.destroy; + let destroyed = 0; + GPUBuffer.prototype.destroy = function () { + destroyed++; + return originalDestroy.apply(this, arguments); + }; + try { + await solve.destroy(); + } finally { + GPUBuffer.prototype.destroy = originalDestroy; + } + assert.ok(destroyed >= 7, `destroy released the executor's buffers (${ destroyed } GPUBuffer.destroy calls)`); + await assert.rejects(solve([1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]), /destroyed/, 'calls after destroy reject'); + await gpu.destroy(); +}); + +webgpuTest('gpu.destroy() reaches a fused pipeline first; destroying it again is safe', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(dbl(x)); + }); + assertClose(assert, await solve([1, 2, 3]), [4, 8, 12], 'runs before teardown'); + assert.equal(solve.executorKind, 'fused-encoder'); + await gpu.destroy(); + await solve.destroy(); + assert.ok(true, 'destroy after gpu.destroy() does not throw'); +}); + +webgpuTest('user kernels stay independently usable while their pipeline is fused', async assert => { + const gpu = new GPU({ mode: 'webgpu' }); + const dbl = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [3] }); + const solve = gpu.createPipeline(function (x) { + return dbl(dbl(x)); + }); + assertClose(assert, await solve([1, 2, 3]), [4, 8, 12], 'pipeline'); + assert.equal(solve.executorKind, 'fused-encoder'); + assertClose(assert, await dbl([5, 6, 7]), [10, 12, 14], 'direct call unaffected'); + assertClose(assert, await solve([2, 2, 2]), [8, 8, 8], 'pipeline again after direct use'); + await gpu.destroy(); +}); From 65ba1e89dea61f5ce7326054d9ab246b67233fb7 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 15:05:02 +0800 Subject: [PATCH 10/16] bench: webgpu pipeline lowering vs per-pass chaining Playwright driver running benchmark-pipeline.mjs's jacobi/heat workloads in headed Chromium (ANGLE Metal): per-pass pipeline:true chaining vs the generic and fused-encoder pipeline executors, checksum-gated against the plain-JS oracle, executorKind asserted, median of 5. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- scripts/benchmark-pipeline-webgpu.mjs | 410 ++++++++++++++++++++++++++ 1 file changed, 410 insertions(+) create mode 100644 scripts/benchmark-pipeline-webgpu.mjs diff --git a/scripts/benchmark-pipeline-webgpu.mjs b/scripts/benchmark-pipeline-webgpu.mjs new file mode 100644 index 00000000..f9332253 --- /dev/null +++ b/scripts/benchmark-pipeline-webgpu.mjs @@ -0,0 +1,410 @@ +#!/usr/bin/env node +// Benchmarks the webgpu fused-encoder pipeline executor against today's +// per-pass kernel chaining and the generic pipeline executor, on the same +// two iterative-stencil workloads as scripts/benchmark-pipeline.mjs, against +// dist/gpu-browser.js in headed Chromium — headless Chromium exposes +// navigator.gpu but requestAdapter() resolves null, so headed is mandatory. +// Prints a GitHub-markdown table plus raw JSON to stdout (progress goes to +// stderr, nothing is written to disk). +// +// npm run make && node scripts/benchmark-pipeline-webgpu.mjs +// +// The workloads are benchmark-pipeline.mjs's jacobi and heat rows verbatim — +// same make(), same fp32-exact constants, same index-weighted checksums, +// same flat-buffer plain-JS oracle — redeclared inside the page function +// because gpu.js parses kernels via Function.prototype.toString and +// Playwright serializes the page function without closures. Methodology +// follows that script: +// - every mode's checksum is validated against the plain-JS oracle +// (relative 1e-3) before timing; a mismatch aborts the run +// - pipeline rows additionally assert executorKind after the validation +// call, so a silent fallback can never be benchmarked under its label +// - median of 5 runs, the validation call serving as compile warmup; wall +// clock only, since GPU timer queries report garbage on ANGLE Metal +// - every timed run is synced by reading back its own result (the per-pass +// row's final toArray(), the pipeline rows' host-array return) +// - every run starts from the pristine grid (the per-pass row re-reads its +// resident u0 handle, the pipeline rows re-sample their arguments), so no +// run inherits a prior run's relaxation +// +// Cost accounting is deliberately tilted against the pipeline, as in the +// Node script: the per-pass row uploads its inputs ONCE at build while +// pipeline rows pay the argument snapshot + upload on EVERY call. Speedups +// are relative to the per-pass row. + +import net from 'node:net'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { chromium } from '@playwright/test'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const PORT = 8099; + +function portListening(port) { + return new Promise(resolve => { + const socket = net.connect({ port, host: '127.0.0.1' }); + socket.once('connect', () => { socket.destroy(); resolve(true); }); + socket.once('error', () => resolve(false)); + }); +} + +// Runs inside the page in ONE session; must stay closure-free. +async function benchInPage() { + const G = window.GPU; + if (!G || !G.prototype || typeof G.prototype.createKernel !== 'function') { + throw new Error('dist/gpu-browser.js did not expose GPU — run npm run make first'); + } + if (!navigator.gpu) throw new Error('navigator.gpu absent'); + const adapter = await navigator.gpu.requestAdapter(); + if (!adapter) throw new Error('no WebGPU adapter (headless or blocklisted)'); + const info = adapter.info || (adapter.requestAdapterInfo ? await adapter.requestAdapterInfo() : null); + const adapterLabel = info + ? [info.vendor, info.architecture, info.device, info.description].filter(Boolean).join(' / ') + : 'adapter present (no info)'; + const log = (...a) => console.log(a.join(' ')); + + const N = 1024; + + function lcg(seed) { + let s = seed >>> 0; + return () => { + s = (s * 1664525 + 1013904223) >>> 0; + return (s >>> 8) / 0x1000000; + }; + } + + // Rows of a flat grid as a 2-D array, which is what a gpu.js kernel + // indexes. subarray, not slice: these are views, so nothing is copied + // here — the pipeline's own call-time snapshot is the copy being priced. + function rows(flat, n) { + const out = []; + for (let y = 0; y < n; y++) out.push(flat.subarray(y * n, y * n + n)); + return out; + } + + function relativeError(a, b) { + const denominator = Math.max(Math.abs(a), Math.abs(b), 1e-20); + return Math.abs(a - b) / denominator; + } + + // gpu.js hands back rows, the oracle hands back one flat array; both + // shapes are walked rather than flattened. Index-weighted so a backend + // that swept only part of the grid cannot match by luck. + function weightedSum(out, squared) { + let acc = 0; + if (ArrayBuffer.isView(out)) { + for (let i = 0; i < out.length; i++) { + const v = squared ? out[i] * out[i] : out[i]; + acc += v * (1 + (i % 17)); + } + } else { + for (let y = 0; y < out.length; y++) { + const row = out[y]; + for (let x = 0; x < row.length; x++) { + const v = squared ? row[x] * row[x] : row[x]; + acc += v * (1 + ((y * N + x) % 17)); + } + } + } + return acc / (N * N); + } + + const identitySource = function (v) { + return v[this.thread.y][this.thread.x]; + }; + + function jacobi() { + const SWEEPS = 512; + const HI = N - 2; + const C = (N - 1) / 2; // grid centre, exact in fp32 + const INV = Math.fround(2 / (N - 1)); + const QS = 1 / 1024; // power of two, exact everywhere + + const sweepSource = function (u, src) { + const x = this.thread.x; + const y = this.thread.y; + // Dirichlet edge, copied through — keeps both ping-pong buffers + // holding a correct edge without either being pre-filled + if (x < 1 || y < 1 || x > this.constants.hi || y > this.constants.hi) { + return u[y][x]; + } + return 0.25 * (u[y - 1][x] + u[y + 1][x] + u[y][x - 1] + u[y][x + 1]) + src[y][x]; + }; + + return { + name: `jacobi ${ N }×${ N }, ${ SWEEPS } sweeps`, + make() { + const rnd = lcg(0x27d4eb2f); + const u0 = new Float32Array(N * N); + const q = new Float32Array(N * N); + for (let y = 0; y < N; y++) { + const sy = (y - C) * INV; + for (let x = 0; x < N; x++) { + const sx = (x - C) * INV; + const i = y * N + x; + u0[i] = 0.5 + 0.25 * Math.sin(3 * Math.PI * sx) * Math.sin(2 * Math.PI * sy) + 0.1 * (rnd() - 0.5); + q[i] = QS * (2 - sx * sx - sy * sy); + } + } + return { u0, q }; + }, + js({ u0, q }) { + // copied, not aliased: both buffers get the boundary because both + // take a turn as the source + let src = new Float32Array(u0); + let dst = new Float32Array(u0); + for (let s = 0; s < SWEEPS; s++) { + for (let y = 1; y <= HI; y++) { + const row = y * N; + for (let x = 1; x <= HI; x++) { + const i = row + x; + dst[i] = 0.25 * (src[i - N] + src[i + N] + src[i - 1] + src[i + 1]) + q[i]; + } + } + const t = src; + src = dst; + dst = t; + } + return src; + }, + reduce(out) { + return weightedSum(out, false); + }, + async perPass(gpu, { u0, q }) { + // two instances of one kernel body: with immutable:false a kernel + // reuses its own output buffer, so one instance cannot both read + // the previous sweep and overwrite it + const settings = { constants: { hi: HI }, output: [N, N], pipeline: true }; + const kA = gpu.createKernel(sweepSource, settings); + const kB = gpu.createKernel(sweepSource, settings); + // two identity uploads, not one called twice: the second call + // would hand back the buffer it filled the first time + const upU = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const upQ = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const u0Handle = await upU(rows(u0, N)); + const qHandle = await upQ(rows(q, N)); + return { + async run() { + // sweep 0 reads the pristine u0 handle and writes kA's own + // buffer, so every run starts from the same grid + let t = u0Handle; + for (let s = 0; s < SWEEPS; s++) t = await (s % 2 === 0 ? kA : kB)(t, qHandle); + return await t.toArray(); + }, + }; + }, + buildPipeline(gpu, { u0, q }) { + // ONE kernel — double-buffering the ping-pong is the plan's business + const sweep = gpu.createKernel(sweepSource, { constants: { hi: HI }, output: [N, N] }); + const solve = gpu.createPipeline(function (u, src) { + for (let s = 0; s < this.constants.sweeps; s++) { + u = sweep(u, src); + } + return u; + }, { constants: { sweeps: SWEEPS } }); + const uRows = rows(u0, N); + const qRows = rows(q, N); + return { shortcut: solve, run: async () => await solve(uRows, qRows) }; + }, + }; + } + + function heat() { + const STEPS = 1024; + const HI = N - 2; + const ALPHA = Math.fround(0.2); // rounded to fp32 once, shared by every column + + const stepSource = function (u) { + const x = this.thread.x; + const y = this.thread.y; + if (x < 1 || y < 1 || x > this.constants.hi || y > this.constants.hi) { + return u[y][x]; + } + const c = u[y][x]; + return c + this.constants.alpha * (u[y - 1][x] + u[y + 1][x] + u[y][x - 1] + u[y][x + 1] - 4 * c); + }; + + return { + name: `heat ${ N }×${ N }, ${ STEPS } steps`, + make() { + const rnd = lcg(0x1b873593); + const u0 = new Float32Array(N * N); + const k = (2 * Math.PI) / 32; // 32-cell wavelength the run annihilates + for (let y = 0; y < N; y++) { + const sy = Math.sin(k * y); + for (let x = 0; x < N; x++) { + u0[y * N + x] = 0.5 + 0.45 * Math.sin(k * x) * sy + 0.05 * (rnd() - 0.5); + } + } + return { u0 }; + }, + js({ u0 }) { + let src = new Float32Array(u0); + let dst = new Float32Array(u0); + for (let s = 0; s < STEPS; s++) { + for (let y = 1; y <= HI; y++) { + const row = y * N; + for (let x = 1; x <= HI; x++) { + const i = row + x; + const c = src[i]; + dst[i] = c + ALPHA * (src[i - N] + src[i + N] + src[i - 1] + src[i + 1] - 4 * c); + } + } + const t = src; + src = dst; + dst = t; + } + return src; + }, + // field energy: diffusion conserves the mean, so a mean-based + // checksum would pass a backend that did nothing; the sum of squares + // falls 17% + reduce(out) { + return weightedSum(out, true); + }, + async perPass(gpu, { u0 }) { + const settings = { constants: { hi: HI, alpha: ALPHA }, output: [N, N], pipeline: true }; + const kA = gpu.createKernel(stepSource, settings); + const kB = gpu.createKernel(stepSource, settings); + const upload = gpu.createKernel(identitySource, { output: [N, N], pipeline: true }); + const u0Handle = await upload(rows(u0, N)); + return { + async run() { + let t = u0Handle; + for (let s = 0; s < STEPS; s++) t = await (s % 2 === 0 ? kA : kB)(t); + return await t.toArray(); + }, + }; + }, + buildPipeline(gpu, { u0 }) { + const step = gpu.createKernel(stepSource, { constants: { hi: HI, alpha: ALPHA }, output: [N, N] }); + const diffuse = gpu.createPipeline(function (u) { + for (let s = 0; s < this.constants.steps; s++) { + u = step(u); + } + return u; + }, { constants: { steps: STEPS } }); + const uRows = rows(u0, N); + return { shortcut: diffuse, run: async () => await diffuse(uRows) }; + }, + }; + } + + const MODES = [ + { label: 'webgpu per-pass', perPass: true }, + { label: 'pipeline generic', kind: 'generic', hook: pipeline => (pipeline._fusionDisabled = true) }, + { label: 'pipeline fused-encoder', kind: 'fused-encoder' }, + ]; + + async function timeRuns(run) { + const times = []; + for (let i = 0; i < 5; i++) { + const start = performance.now(); + await run(); + times.push(performance.now() - start); + } + times.sort((a, b) => a - b); + return +times[Math.floor(times.length / 2)].toFixed(2); + } + + const table = []; + for (const workload of [jacobi(), heat()]) { + const inputs = workload.make(); + const row = { name: workload.name, modes: {} }; + // plain-JS oracle: reference only, computed once — the columns are all + // webgpu + const expected = workload.reduce(workload.js(inputs)); + log(workload.name, '/ plain-JS reference checksum:', expected.toFixed(6)); + for (const mode of MODES) { + const gpu = new G({ mode: 'webgpu' }); + let built; + if (mode.perPass) { + built = await workload.perPass(gpu, inputs); + } else { + built = workload.buildPipeline(gpu, inputs); + if (mode.hook) mode.hook(built.shortcut.pipeline); + } + // correctness gate before any timing; also the compile warmup + const checksum = workload.reduce(await built.run()); + const err = relativeError(expected, checksum); + if (err > 1e-3) { + throw new Error(`CHECKSUM MISMATCH in ${ workload.name } (${ mode.label }): ${ checksum } vs ${ expected } (relative ${ err })`); + } + if (mode.kind && built.shortcut.executorKind !== mode.kind) { + throw new Error(`EXECUTOR MISMATCH in ${ workload.name } (${ mode.label }): got '${ built.shortcut.executorKind }' (fallbackReason: ${ built.shortcut.fallbackReason })`); + } + const ms = await timeRuns(built.run); + row.modes[mode.label] = { ms, checksum }; + log(workload.name, '/', mode.label + ':', ms, 'ms (checksum', checksum.toFixed(6) + ')'); + await gpu.destroy(); + } + table.push(row); + } + + return { adapterLabel, userAgent: navigator.userAgent, table }; +} + +// -- report ---------------------------------------------------------------- +function printReport(data, chromiumVersion) { + const labels = ['webgpu per-pass', 'pipeline generic', 'pipeline fused-encoder']; + const lines = []; + lines.push('### Benchmarks — webgpu pipeline lowering'); + lines.push(''); + lines.push('- Chromium ' + chromiumVersion + ' (headed)'); + lines.push('- WebGPU adapter: ' + data.adapterLabel); + lines.push('- median of 5; every run synced by reading back its own result; checksums validated against the plain-JS oracle before timing'); + lines.push(''); + lines.push(`| Workload | ${ labels.join(' | ') } |`); + lines.push(`|---|${ labels.map(() => '---').join('|') }|`); + for (const row of data.table) { + const baseline = row.modes['webgpu per-pass'].ms; + lines.push(`| ${ row.name } | ${ labels.map(label => { + const ms = row.modes[label].ms; + const speedup = label === 'webgpu per-pass' ? ' (1×)' : ` (${ (baseline / ms).toFixed(2) }×)`; + return `${ ms } ms${ speedup }`; + }).join(' | ') } |`); + } + lines.push(''); + lines.push(JSON.stringify(data.table, null, 2)); + process.stdout.write(lines.join('\n') + '\n'); +} + +// -- driver ---------------------------------------------------------------- +async function main() { + let devServer = null; + if (await portListening(PORT)) { + process.stderr.write('dev server already listening on :' + PORT + '\n'); + } else { + process.stderr.write('starting dev server on :' + PORT + '\n'); + devServer = spawn(process.execPath, [path.join(ROOT, 'scripts', 'dev.js')], { + cwd: ROOT, + env: { ...process.env, PORT: String(PORT) }, + stdio: ['ignore', 'ignore', 'inherit'], + }); + const deadline = Date.now() + 10000; + while (!(await portListening(PORT))) { + if (Date.now() > deadline) throw new Error('dev server did not start on :' + PORT); + await new Promise(r => setTimeout(r, 200)); + } + } + + const browser = await chromium.launch({ headless: false, args: ['--use-angle=metal'] }); + try { + const page = await browser.newPage(); + page.on('console', msg => process.stderr.write('[page] ' + msg.text() + '\n')); + page.on('pageerror', err => process.stderr.write('[pageerror] ' + err.message + '\n')); + await page.goto('http://localhost:' + PORT + '/test/'); + await page.addScriptTag({ url: '/dist/gpu-browser.js' }); + const data = await page.evaluate(benchInPage); + printReport(data, browser.version()); + } finally { + await browser.close(); + if (devServer) devServer.kill(); + } +} + +main().catch(err => { + process.stderr.write('\nBENCHMARK ABORTED: ' + (err && err.stack || err) + '\n'); + process.exit(1); +}); From 3b471882a994ad5b798caeec5dc505b229516a9b Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 15:36:22 +0800 Subject: [PATCH 11/16] fix(pipeline): the three findings of the webgpu lowering review Oversize pipeline arguments degrade to the generic executor with a named reason instead of resolving silent zeros -- past the device's storage-binding limit, createBuffer succeeds but the bind group fails async validation and every read maps zeros; the fused compile now runs the kernel's own size check first. An argument bound ONLY in the results never gets an arg region, so the resident-handle screens missed it: a GPU-resident handle in a result seat resolved as a deleted buffer. Result seats are now screened at compile and per call exactly like step-bound ones. An Input returned as a result resolved to the Input instance under the fused executors while the generic executor erected it to rows; both fused paths (webgpu and webasm) now unwrap toArray()-bearing result values for generic parity. All three reproduced in headed Chrome before fixing, re-verified after, and pinned by browser-gated regression tests. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 32 +++++++++++-- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 32 +++++++++++-- dist/gpu-browser.min.js | 4 +- src/backend/web-assembly/pipeline-executor.js | 13 ++++- src/backend/web-gpu/pipeline-executor.js | 48 ++++++++++++++++++- test/features/pipeline/fused-webgpu.js | 35 +++++++++++++- 7 files changed, 153 insertions(+), 15 deletions(-) diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 4c65b0a8..dd65082b 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 15:31:57 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -19129,6 +19129,10 @@ this.recompilable = Boolean(recompilable); } }; + function unwrapResultValue(value) { + if (value && typeof value.toArray === "function") return value.toArray(); + return value; + } function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); while (dims.length < 3) dims.push(1); @@ -19656,7 +19660,7 @@ if (read.kind === "step") { const data = f32.slice(read.base, read.base + read.count); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); - } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } else if (read.kind === "arg") values[i] = unwrapResultValue(args[read.index]); else values[i] = unwrapResultValue(read.value); } if (results.kind === "single") return values[0]; if (results.kind === "array") return values; @@ -19697,6 +19701,15 @@ const {FusionFallback: FusionFallback} = require_pipeline_executor$1(); const USAGE_STORAGE = 128; const MAP_MODE_READ = 1; + function unwrapResultValue(value) { + if (value && typeof value.toArray === "function") return value.toArray(); + return value; + } + function checkStorageSize(device, byteLength, what) { + const limits = device.limits; + const max = Math.min(limits.maxStorageBufferBindingSize, limits.maxBufferSize); + if (byteLength > max) throw new FusionFallback(`${what} needs ${byteLength} bytes but this device allows ${max} per storage buffer`); + } function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); while (dims.length < 3) dims.push(1); @@ -19765,6 +19778,13 @@ if (binding.source === "pipelineArg" && isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); } } + this._resultArgIndexes = []; + for (let i = 0; i < plan.results.entries.length; i++) { + const binding = plan.results.entries[i].binding; + if (binding.source !== "pipelineArg") continue; + if (isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); + this._resultArgIndexes.push(binding.index); + } const programs = new Map; const cloneClaimed = new Array(plan.kernels.length).fill(false); const stepPrograms = new Array(plan.steps.length); @@ -19848,6 +19868,7 @@ if (!region) { const dims = valueDimensions(args[binding.index]); const flatLength = dims[0] * dims[1] * dims[2]; + checkStorageSize(device, flatLength * 4, `pipeline argument ${binding.index}`); region = { dims: dims, flatLength: flatLength, @@ -19866,6 +19887,7 @@ if (!literal) { const dims = valueDimensions(binding.value); const flatLength = dims[0] * dims[1] * dims[2]; + checkStorageSize(device, flatLength * 4, "a literal array argument"); const buffer = device.createBuffer({ size: Math.max(flatLength * 4, 4), usage: USAGE_STORAGE, @@ -20058,6 +20080,10 @@ if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); } for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + for (let i = 0; i < this._resultArgIndexes.length; i++) { + const index = this._resultArgIndexes[i]; + if (isResidentHandle(args[index])) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); + } } _writeScalar(u32, i32, f32, record, value) { const slot = record.offset / 4; @@ -20114,7 +20140,7 @@ if (read.kind === "step") { const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); - } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } else if (read.kind === "arg") values[i] = unwrapResultValue(args[read.index]); else values[i] = unwrapResultValue(read.value); } if (results.kind === "single") return values[0]; if (results.kind === "array") return values; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 35028c5c..acd355eb 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 15:31:57 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function u(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function l(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}u[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=d.get(e);return void 0===t&&(t=d.size,d.set(e,t)),t},m=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),v=null!==d.randomSeedOffset&&null===p.randomSeed,T=l.id+":"+g.map(f).join(",")+">"+f(x)+":"+b+(v?"#"+n:"");let S=m.get(T);if(!S){const e=new ArrayBuffer(d.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=p._computeDispatch(p.threadDim);t[0]=p.threadDim[0],t[1]=p.threadDim[1],t[2]=p.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:d.byteLength,usage:72}),l=o.length>0||v;l||c.writeBuffer(u,0,e);const f=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=u[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:g,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return g+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),g>0&&(this._staging=h.createBuffer({size:g,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index b37d4622..cf845687 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 15:31:56 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -23326,6 +23326,10 @@ this.recompilable = Boolean(recompilable); } }; + function unwrapResultValue(value) { + if (value && typeof value.toArray === "function") return value.toArray(); + return value; + } function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); while (dims.length < 3) dims.push(1); @@ -23853,7 +23857,7 @@ if (read.kind === "step") { const data = f32.slice(read.base, read.base + read.count); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); - } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } else if (read.kind === "arg") values[i] = unwrapResultValue(args[read.index]); else values[i] = unwrapResultValue(read.value); } if (results.kind === "single") return values[0]; if (results.kind === "array") return values; @@ -23894,6 +23898,15 @@ const {FusionFallback: FusionFallback} = require_pipeline_executor$1(); const USAGE_STORAGE = 128; const MAP_MODE_READ = 1; + function unwrapResultValue(value) { + if (value && typeof value.toArray === "function") return value.toArray(); + return value; + } + function checkStorageSize(device, byteLength, what) { + const limits = device.limits; + const max = Math.min(limits.maxStorageBufferBindingSize, limits.maxBufferSize); + if (byteLength > max) throw new FusionFallback(`${what} needs ${byteLength} bytes but this device allows ${max} per storage buffer`); + } function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); while (dims.length < 3) dims.push(1); @@ -23962,6 +23975,13 @@ if (binding.source === "pipelineArg" && isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); } } + this._resultArgIndexes = []; + for (let i = 0; i < plan.results.entries.length; i++) { + const binding = plan.results.entries[i].binding; + if (binding.source !== "pipelineArg") continue; + if (isResidentHandle(args[binding.index])) throw new FusionFallback(`pipeline argument ${binding.index} is a GPU-resident handle; the fused encoder takes plain arrays`); + this._resultArgIndexes.push(binding.index); + } const programs = new Map; const cloneClaimed = new Array(plan.kernels.length).fill(false); const stepPrograms = new Array(plan.steps.length); @@ -24045,6 +24065,7 @@ if (!region) { const dims = valueDimensions(args[binding.index]); const flatLength = dims[0] * dims[1] * dims[2]; + checkStorageSize(device, flatLength * 4, `pipeline argument ${binding.index}`); region = { dims: dims, flatLength: flatLength, @@ -24063,6 +24084,7 @@ if (!literal) { const dims = valueDimensions(binding.value); const flatLength = dims[0] * dims[1] * dims[2]; + checkStorageSize(device, flatLength * 4, "a literal array argument"); const buffer = device.createBuffer({ size: Math.max(flatLength * 4, 4), usage: USAGE_STORAGE, @@ -24255,6 +24277,10 @@ if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); } for (const slot of this._argScalarSlots.values()) if (!scalarMatches(slot.type, args[slot.index])) throw new FusionFallback(`pipeline argument ${slot.index} is no longer of type ${slot.type}`, true); + for (let i = 0; i < this._resultArgIndexes.length; i++) { + const index = this._resultArgIndexes[i]; + if (isResidentHandle(args[index])) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); + } } _writeScalar(u32, i32, f32, record, value) { const slot = record.offset / 4; @@ -24311,7 +24337,7 @@ if (read.kind === "step") { const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); - } else if (read.kind === "arg") values[i] = args[read.index]; else values[i] = read.value; + } else if (read.kind === "arg") values[i] = unwrapResultValue(args[read.index]); else values[i] = unwrapResultValue(read.value); } if (results.kind === "single") return values[0]; if (results.kind === "array") return values; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 4f3c7ebe..0c565166 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 14:59:52 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 15:31:56 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function p(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function u(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function l(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}u[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=d.get(e);return void 0===t&&(t=d.size,d.set(e,t)),t},m=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),v=null!==d.randomSeedOffset&&null===p.randomSeed,S=l.id+":"+g.map(f).join(",")+">"+f(x)+":"+b+(v?"#"+r:"");let T=m.get(S);if(!T){const e=new ArrayBuffer(d.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=p._computeDispatch(p.threadDim);t[0]=p.threadDim[0],t[1]=p.threadDim[1],t[2]=p.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:d.byteLength,usage:72}),l=o.length>0||v;l||c.writeBuffer(u,0,e);const f=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=u[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:g,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return g+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),g>0&&(this._staging=h.createBuffer({size:g,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/backend/web-assembly/pipeline-executor.js b/src/backend/web-assembly/pipeline-executor.js index 27b7a260..1757dff8 100644 --- a/src/backend/web-assembly/pipeline-executor.js +++ b/src/backend/web-assembly/pipeline-executor.js @@ -47,6 +47,15 @@ class FusionFallback extends Error { } } +// generic-executor parity: any result value exposing toArray() reads back +// (an Input resolves to its erected rows, not the Input instance) +function unwrapResultValue(value) { + if (value && typeof value.toArray === 'function') { + return value.toArray(); + } + return value; +} + function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : @@ -728,9 +737,9 @@ class WebAssemblyPipelineExecutor { const data = f32.slice(read.base, read.base + read.count); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); } else if (read.kind === 'arg') { - values[i] = args[read.index]; + values[i] = unwrapResultValue(args[read.index]); } else { - values[i] = read.value; + values[i] = unwrapResultValue(read.value); } } if (results.kind === 'single') return values[0]; diff --git a/src/backend/web-gpu/pipeline-executor.js b/src/backend/web-gpu/pipeline-executor.js index b688130a..16531d8a 100644 --- a/src/backend/web-gpu/pipeline-executor.js +++ b/src/backend/web-gpu/pipeline-executor.js @@ -24,6 +24,27 @@ const USAGE_COPY_DST = 0x0008; const USAGE_MAP_READ = 0x0001; const MAP_MODE_READ = 0x0001; +// the generic executor reads back any result value exposing toArray() (an +// Input resolves to its erected rows, not the Input instance); the fused +// executors must resolve identical shapes. Resident handles never reach +// this -- the compile and per-call guards degrade them first. +function unwrapResultValue(value) { + if (value && typeof value.toArray === 'function') { + return value.toArray(); + } + return value; +} + +function checkStorageSize(device, byteLength, what) { + const limits = device.limits; + const max = Math.min(limits.maxStorageBufferBindingSize, limits.maxBufferSize); + if (byteLength > max) { + // degrade rather than throw the kernel's error: the generic executor + // routes through the kernel's own path, which reports it loudly + throw new FusionFallback(`${ what } needs ${ byteLength } bytes but this device allows ${ max } per storage buffer`); + } +} + function valueDimensions(value) { const dims = value instanceof Input ? Array.from(value.size) : @@ -123,6 +144,18 @@ class WebGPUPipelineExecutor { } } } + // an argument bound ONLY in the results never gets an arg region, so the + // per-call checks below would miss it -- remember its seats and screen + // them exactly like step-bound ones + this._resultArgIndexes = []; + for (let i = 0; i < plan.results.entries.length; i++) { + const binding = plan.results.entries[i].binding; + if (binding.source !== 'pipelineArg') continue; + if (isResidentHandle(args[binding.index])) { + throw new FusionFallback(`pipeline argument ${ binding.index } is a GPU-resident handle; the fused encoder takes plain arrays`); + } + this._resultArgIndexes.push(binding.index); + } // a program is a plan kernel built for one argument-type signature: the // kernel's own build() ran (WGSL, compute pipeline, constant buffers), // but its run() never will — the executor encodes the passes itself @@ -219,6 +252,10 @@ class WebGPUPipelineExecutor { if (!region) { const dims = valueDimensions(args[binding.index]); const flatLength = dims[0] * dims[1] * dims[2]; + // over the storage-binding limit, createBuffer succeeds but the + // bind group fails ASYNC validation and every read maps zeros -- + // the direct kernel throws here, so the fused path must too + checkStorageSize(device, flatLength * 4, `pipeline argument ${ binding.index }`); region = { dims, flatLength, @@ -237,6 +274,7 @@ class WebGPUPipelineExecutor { if (!literal) { const dims = valueDimensions(binding.value); const flatLength = dims[0] * dims[1] * dims[2]; + checkStorageSize(device, flatLength * 4, 'a literal array argument'); const buffer = device.createBuffer({ size: Math.max(flatLength * 4, 4), usage: USAGE_STORAGE, @@ -461,6 +499,12 @@ class WebGPUPipelineExecutor { throw new FusionFallback(`pipeline argument ${ slot.index } is no longer of type ${ slot.type }`, true); } } + for (let i = 0; i < this._resultArgIndexes.length; i++) { + const index = this._resultArgIndexes[i]; + if (isResidentHandle(args[index])) { + throw new FusionFallback(`pipeline argument ${ index } is now a GPU-resident handle`, true); + } + } } _writeScalar(u32, i32, f32, record, value) { @@ -548,9 +592,9 @@ class WebGPUPipelineExecutor { const data = new Float32Array(mapped.slice(read.offset, read.offset + read.byteLength)); values[i] = read.kernel._shapeOutput(data, read.output, read.componentCount); } else if (read.kind === 'arg') { - values[i] = args[read.index]; + values[i] = unwrapResultValue(args[read.index]); } else { - values[i] = read.value; + values[i] = unwrapResultValue(read.value); } } if (results.kind === 'single') return values[0]; diff --git a/test/features/pipeline/fused-webgpu.js b/test/features/pipeline/fused-webgpu.js index c09ed48b..547b18c1 100644 --- a/test/features/pipeline/fused-webgpu.js +++ b/test/features/pipeline/fused-webgpu.js @@ -1,5 +1,5 @@ const { assert, skip, test, module: describe } = require('qunit'); -const { GPU } = require('../../../src'); +const { GPU, input } = require('../../../src'); describe('features: pipeline fused webgpu encoder'); @@ -409,3 +409,36 @@ webgpuTest('user kernels stay independently usable while their pipeline is fused assertClose(assert, await solve([2, 2, 2]), [8, 8, 8], 'pipeline again after direct use'); await gpu.destroy(); }); + +webgpuTest('a handle bound only in the results degrades with a named reason', async assert => { + if (!(await webgpuAdapter(assert))) return; + const gpu = new GPU({ mode: 'webgpu' }); + const k = gpu.createKernel(function (a) { return a[this.thread.x] * 2; }, { output: [4] }); + const p = gpu.createPipeline(function (x, y) { return { out: k(x), copy: y }; }); + const first = await p([1, 2, 3, 4], [9, 8, 7, 6]); + assert.equal(p.executorKind, 'fused-encoder'); + assert.deepEqual(Array.from(first.copy), [9, 8, 7, 6]); + const producer = gpu.createKernel(function () { return this.thread.x + 10; }, { output: [4], pipeline: true }); + const handle = await producer(); + // the result-only seat never gets an arg region, so without its own + // screen the fused path resolved a deleted buffer handle here + const second = await p([1, 2, 3, 4], handle); + assert.equal(p.executorKind, 'generic'); + assert.ok(/GPU-resident handle/.test(p.fallbackReason), p.fallbackReason); + const copy = typeof second.copy.toArray === 'function' ? await second.copy.toArray() : second.copy; + assert.deepEqual(Array.from(copy), [10, 11, 12, 13]); + await gpu.destroy(); +}); + +webgpuTest('an Input returned as a result resolves to plain rows, generic-parity', async assert => { + if (!(await webgpuAdapter(assert))) return; + const gpu = new GPU({ mode: 'webgpu' }); + const g = gpu.createKernel(function (m) { return m[this.thread.y][this.thread.x] + 1; }, { output: [3, 2] }); + const p = gpu.createPipeline(function (m) { return { orig: m, out: g(m) }; }); + const res = await p(input(new Float32Array([0, 1, 2, 10, 11, 12]), [3, 2])); + assert.equal(p.executorKind, 'fused-encoder'); + assert.deepEqual(Array.from(res.orig[0]), [0, 1, 2], 'the Input erected to rows, not the instance'); + assert.deepEqual(Array.from(res.orig[1]), [10, 11, 12]); + assert.deepEqual(Array.from(res.out[1]), [11, 12, 13]); + await gpu.destroy(); +}); From 0d5b1051fd31ece1cba90d432262bbdeb735f94a Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 16:50:27 +0800 Subject: [PATCH 12/16] perf(pipeline): mutable statically-typed clones in the generic executor The generic executor forced immutable: true on its plan clones, which on GL allocated and destroyed one full-size texture PER PLAN STEP -- 0.99 create/delete pairs per step measured over a 200-step ping-pong, a 3-29x loss against hand-rolled two-kernel loops and an adoption blocker for GL columns (PR #871 review comment). Static liveness is what makes mutability safe: assignBuffers already guarantees no step reads a slot while that slot's writer renders. The executor now clones per (kernel, seat signature, output slot) with immutable: false and dynamicArguments: false -- each clone owns one output for the plan's life and sees one argument-type signature -- and array pipeline arguments upload ONCE per call through lazy identity kernels on backends where uploads cost (GL, webgpu). Together that is mechanically the hand-rolled upU/upQ + kA/kB pattern, generated. Measured on the comment's own instrumentation (200-step 1024^2 jacobi, headlessgl): texture churn 0.99/step -> 0.00/step; wall clock 248 ms -> 51 ms, now at parity-or-better with the hand-rolled loop (67 ms same session). Layer shares: mutable clones -35%, static types -35% more, once-per-call uploads -68% of the remainder. Static shapes need a drift story: argument size changes rebuild the generic clones (the fused executors' recompile contract), and cpu results copy on readback so a held result survives the next call. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 94 +++++++++++++--- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 94 +++++++++++++--- dist/gpu-browser.min.js | 4 +- src/pipeline.js | 150 ++++++++++++++++++++++++-- test/features/pipeline/correctness.js | 29 +++++ 6 files changed, 336 insertions(+), 39 deletions(-) diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index dd65082b..7f9d1a6a 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 15:31:57 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -20178,6 +20178,7 @@ }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); + const {utils: utils} = require_utils(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; const MSG_HANDLE_PRIMITIVE = "pipeline intermediate results cannot be used in arithmetic or conditions during orchestration"; const MSG_MATH_RANDOM = "Math.random() is not allowed during pipeline orchestration; orchestration must be deterministic"; @@ -20474,9 +20475,23 @@ buffers: buffers, results: results, kernels: kernels, - held: trace.held + held: trace.held, + genericClones: new Map }; } + _genericClone(plan, step) { + const signature = step.argBindings.map(binding => binding.source === "step" ? "T" : binding.source === "pipelineArg" ? "a" + binding.index : "l").join(","); + const key = step.kernel + ":" + step.outputBuffer + ":" + signature; + let clone = plan.genericClones.get(key); + if (!clone) { + clone = this._cloneKernel(plan.kernels[step.kernel].clone, { + immutable: false, + dynamicArguments: false + }); + plan.genericClones.set(key, clone); + } + return clone; + } _prepareExecutor(args) { if (this._fusionDisabled) { this._executor = false; @@ -20511,14 +20526,14 @@ this.executorKind = "generic"; this.fallbackReason = reason; } - _cloneKernel(shortcut) { + _cloneKernel(shortcut, overrides) { const kernel = shortcut.kernel; - const settings = { + const settings = Object.assign({ output: Array.from(kernel.output), pipeline: true, immutable: true, dynamicArguments: true - }; + }, overrides || {}); const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug", "randomSeed", "returnType" ]; if (kernel.declaredArgumentTypes) settings.argumentTypes = kernel.declaredArgumentTypes.slice(); for (let i = 0; i < optional.length; i++) { @@ -20527,8 +20542,55 @@ } return this.gpu.createKernel(kernel.source, settings); } + _uploadArg(plan, index, value) { + const key = "up:" + index; + let upload = plan.genericClones.get(key); + if (!upload) { + const dims = argDimensions(value); + const source = dims[2] > 1 ? "function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }" : dims[1] > 1 ? "function (v) { return v[this.thread.y][this.thread.x]; }" : "function (v) { return v[this.thread.x]; }"; + const output = dims[2] > 1 ? [ dims[0], dims[1], dims[2] ] : dims[1] > 1 ? [ dims[0], dims[1] ] : [ dims[0] ]; + upload = this.gpu.createKernel(source, { + output: output, + pipeline: true, + immutable: false + }); + plan.genericClones.set(key, upload); + } + return upload(value); + } async _executeGeneric(plan, args) { const slots = new Array(plan.buffers.length).fill(null); + if (!plan.genericArgDims) plan.genericArgDims = new Map; + for (let i = 0; i < args.length; i++) { + const value = args[i]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + const dims = argDimensions(value).join("x"); + const known = plan.genericArgDims.get(i); + if (known === void 0) plan.genericArgDims.set(i, dims); else if (known !== dims) { + const gpuKernels = this.gpu && this.gpu.kernels; + for (const clone of plan.genericClones.values()) if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + plan.genericClones.clear(); + plan.genericArgDims = new Map([ [ i, dims ] ]); + break; + } + } + const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; + const uploadsPay = backendMode === "gpu" || backendMode === "webgpu"; + const uploaded = new Array(args.length).fill(null); + if (uploadsPay) for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== "pipelineArg" || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + let handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === "function") handle = await handle; + uploaded[binding.index] = handle; + } + } try { for (let i = 0; i < plan.steps.length; i++) { const step = plan.steps[i]; @@ -20536,11 +20598,10 @@ const resolved = new Array(bindings.length); for (let j = 0; j < bindings.length; j++) { const binding = bindings[j]; - if (binding.source === "pipelineArg") resolved[j] = args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; + if (binding.source === "pipelineArg") resolved[j] = uploaded[binding.index] || args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; } - let output = plan.kernels[step.kernel].clone.apply(null, resolved); + let output = this._genericClone(plan, step).apply(null, resolved); if (output && typeof output.then === "function") output = await output; - releaseValue(slots[step.outputBuffer]); slots[step.outputBuffer] = output; } const results = plan.results; @@ -20552,7 +20613,7 @@ if (value && typeof value.toArray === "function") { value = value.toArray(); if (value && typeof value.then === "function") value = await value; - } + } else if (binding.source === "step") value = copyPlainResult(value); values[i] = value; } if (results.kind === "single") return values[0]; @@ -20561,7 +20622,7 @@ for (let i = 0; i < results.entries.length; i++) shaped[results.entries[i].key] = values[i]; return shaped; } finally { - for (let i = 0; i < slots.length; i++) releaseValue(slots[i]); + slots.length = 0; } } _releasePlan() { @@ -20576,12 +20637,21 @@ const clone = kernels[i].clone; if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); } + for (const clone of this.plan.genericClones.values()) if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + this.plan.genericClones.clear(); if (this.plan.held) releaseSnapshots(this.plan.held); this.plan = null; } }; - function releaseValue(value) { - if (value && typeof value.delete === "function") value.delete(); + function argDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function copyPlainResult(value) { + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(copyPlainResult); + return value; } function noop() {} module.exports = { diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index acd355eb..f128c2eb 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 15:31:57 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),s="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(s)},set(){throw new Error(s)},ownKeys(){throw new Error(s)},has(){throw new Error(s)},getOwnPropertyDescriptor(){throw new Error(s)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>d(r),()=>d(r)),this._tail=n.then(g,g),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(i);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(i);return{kind:"object",entries:n}}throw new Error(i)}(e,n),a=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:s,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,r={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(r.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>m(r),()=>m(r)),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}async _executeGeneric(e,t){const n=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===s||"webgpu"===s,a=new Array(t.length).fill(null);if(i)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index cf845687..c6933a85 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 15:31:56 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -24375,6 +24375,7 @@ }); var require_pipeline = __commonJSMin((exports, module) => { const {Input: Input} = require_input(); + const {utils: utils} = require_utils(); const MSG_HANDLE_READ = "pipeline intermediate results cannot be read during orchestration"; const MSG_HANDLE_PRIMITIVE = "pipeline intermediate results cannot be used in arithmetic or conditions during orchestration"; const MSG_MATH_RANDOM = "Math.random() is not allowed during pipeline orchestration; orchestration must be deterministic"; @@ -24671,9 +24672,23 @@ buffers: buffers, results: results, kernels: kernels, - held: trace.held + held: trace.held, + genericClones: new Map }; } + _genericClone(plan, step) { + const signature = step.argBindings.map(binding => binding.source === "step" ? "T" : binding.source === "pipelineArg" ? "a" + binding.index : "l").join(","); + const key = step.kernel + ":" + step.outputBuffer + ":" + signature; + let clone = plan.genericClones.get(key); + if (!clone) { + clone = this._cloneKernel(plan.kernels[step.kernel].clone, { + immutable: false, + dynamicArguments: false + }); + plan.genericClones.set(key, clone); + } + return clone; + } _prepareExecutor(args) { if (this._fusionDisabled) { this._executor = false; @@ -24708,14 +24723,14 @@ this.executorKind = "generic"; this.fallbackReason = reason; } - _cloneKernel(shortcut) { + _cloneKernel(shortcut, overrides) { const kernel = shortcut.kernel; - const settings = { + const settings = Object.assign({ output: Array.from(kernel.output), pipeline: true, immutable: true, dynamicArguments: true - }; + }, overrides || {}); const optional = [ "constants", "constantTypes", "precision", "loopMaxIterations", "strictIntegers", "fixIntegerDivisionAccuracy", "optimizeFloatMemory", "tactic", "functions", "nativeFunctions", "injectedNative", "debug", "randomSeed", "returnType" ]; if (kernel.declaredArgumentTypes) settings.argumentTypes = kernel.declaredArgumentTypes.slice(); for (let i = 0; i < optional.length; i++) { @@ -24724,8 +24739,55 @@ } return this.gpu.createKernel(kernel.source, settings); } + _uploadArg(plan, index, value) { + const key = "up:" + index; + let upload = plan.genericClones.get(key); + if (!upload) { + const dims = argDimensions(value); + const source = dims[2] > 1 ? "function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }" : dims[1] > 1 ? "function (v) { return v[this.thread.y][this.thread.x]; }" : "function (v) { return v[this.thread.x]; }"; + const output = dims[2] > 1 ? [ dims[0], dims[1], dims[2] ] : dims[1] > 1 ? [ dims[0], dims[1] ] : [ dims[0] ]; + upload = this.gpu.createKernel(source, { + output: output, + pipeline: true, + immutable: false + }); + plan.genericClones.set(key, upload); + } + return upload(value); + } async _executeGeneric(plan, args) { const slots = new Array(plan.buffers.length).fill(null); + if (!plan.genericArgDims) plan.genericArgDims = new Map; + for (let i = 0; i < args.length; i++) { + const value = args[i]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + const dims = argDimensions(value).join("x"); + const known = plan.genericArgDims.get(i); + if (known === void 0) plan.genericArgDims.set(i, dims); else if (known !== dims) { + const gpuKernels = this.gpu && this.gpu.kernels; + for (const clone of plan.genericClones.values()) if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + plan.genericClones.clear(); + plan.genericArgDims = new Map([ [ i, dims ] ]); + break; + } + } + const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; + const uploadsPay = backendMode === "gpu" || backendMode === "webgpu"; + const uploaded = new Array(args.length).fill(null); + if (uploadsPay) for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== "pipelineArg" || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + let handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === "function") handle = await handle; + uploaded[binding.index] = handle; + } + } try { for (let i = 0; i < plan.steps.length; i++) { const step = plan.steps[i]; @@ -24733,11 +24795,10 @@ const resolved = new Array(bindings.length); for (let j = 0; j < bindings.length; j++) { const binding = bindings[j]; - if (binding.source === "pipelineArg") resolved[j] = args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; + if (binding.source === "pipelineArg") resolved[j] = uploaded[binding.index] || args[binding.index]; else if (binding.source === "step") resolved[j] = slots[plan.steps[binding.step].outputBuffer]; else resolved[j] = binding.value; } - let output = plan.kernels[step.kernel].clone.apply(null, resolved); + let output = this._genericClone(plan, step).apply(null, resolved); if (output && typeof output.then === "function") output = await output; - releaseValue(slots[step.outputBuffer]); slots[step.outputBuffer] = output; } const results = plan.results; @@ -24749,7 +24810,7 @@ if (value && typeof value.toArray === "function") { value = value.toArray(); if (value && typeof value.then === "function") value = await value; - } + } else if (binding.source === "step") value = copyPlainResult(value); values[i] = value; } if (results.kind === "single") return values[0]; @@ -24758,7 +24819,7 @@ for (let i = 0; i < results.entries.length; i++) shaped[results.entries[i].key] = values[i]; return shaped; } finally { - for (let i = 0; i < slots.length; i++) releaseValue(slots[i]); + slots.length = 0; } } _releasePlan() { @@ -24773,12 +24834,21 @@ const clone = kernels[i].clone; if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); } + for (const clone of this.plan.genericClones.values()) if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + this.plan.genericClones.clear(); if (this.plan.held) releaseSnapshots(this.plan.held); this.plan = null; } }; - function releaseValue(value) { - if (value && typeof value.delete === "function") value.delete(); + function argDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) dims.push(1); + return dims; + } + function copyPlainResult(value) { + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(copyPlainResult); + return value; } function noop() {} module.exports = { diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 0c565166..f64ee56c 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 15:31:56 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),n="pipeline intermediate results cannot be read during orchestration",i="a pipeline must return a handle, or an Array or plain object of handles",a="pipeline has been destroyed",o="the orchestration function must be synchronous; async functions and generators cannot be traced",u="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var l=class{};let h=null;var c=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new l),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(n)},set(){throw new Error(n)},ownKeys(){throw new Error(n)},has(){throw new Error(n)},getOwnPropertyDescriptor(){throw new Error(n)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ep(e,t)):e}function d(e){for(let t=0;t{if(this.destroyed)throw new Error(a);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>d(s),()=>d(s)),this._tail=r.then(g,g),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(a));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new c(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof l)throw new Error(u);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(o);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(i);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(i);return{kind:"object",entries:r}}throw new Error(i)}(e,r),a=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),p=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:a,results:n,kernels:p,held:e.held}}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e){const t=e.kernel,s={output:Array.from(t.output),pipeline:!0,immutable:!0,dynamicArguments:!0},r=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];t.declaredArgumentTypes&&(s.argumentTypes=t.declaredArgumentTypes.slice());for(let e=0;e{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>m(s),()=>m(s)),this._tail=r.then(b,b),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}async _executeGeneric(e,t){const r=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let r=0;r0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===n||"webgpu"===n,a=new Array(t.length).fill(null);if(i)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/pipeline.js b/src/pipeline.js index 5041a2b0..926543cc 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -1,4 +1,5 @@ const { Input } = require('./input'); +const { utils } = require('./utils'); /** * Pipeline compilation (docs/design/pipeline-compilation.md): the @@ -505,9 +506,43 @@ class Pipeline { results, kernels, held: trace.held, + // the generic executor's mutable per-(kernel, output-slot) clones, + // created lazily on first generic run; see _genericClone + genericClones: new Map(), }; } + /** + * The generic executor's writer for one (kernel, seat signature, output + * slot) triple. One MUTABLE, STATICALLY-TYPED clone per triple reproduces + * the hand-rolled two-kernel ping-pong mechanically: each clone owns one + * output texture/array for the life of the plan (steady state allocates + * nothing per step) and sees one argument-type signature (no per-call + * dynamicArguments re-typing -- the forced re-typing was most of a 7x + * loss even after the texture churn was gone). Static liveness + * (assignBuffers) is what makes mutability safe: no step ever reads a + * slot while that slot's writer renders. Argument drift across CALLS is + * the clones' own switch machinery's business, as for any kernel. + * @param {Object} plan + * @param {Object} step + * @returns {IKernelRunShortcut} + */ + _genericClone(plan, step) { + // seat sources are plan-static: a step-fed seat is a pipeline handle, + // a pipelineArg seat types with that argument, a literal is frozen + const signature = step.argBindings.map(binding => + binding.source === 'step' ? 'T' : + binding.source === 'pipelineArg' ? 'a' + binding.index : + 'l').join(','); + const key = step.kernel + ':' + step.outputBuffer + ':' + signature; + let clone = plan.genericClones.get(key); + if (!clone) { + clone = this._cloneKernel(plan.kernels[step.kernel].clone, { immutable: false, dynamicArguments: false }); + plan.genericClones.set(key, clone); + } + return clone; + } + /** * Attempts the backend's fused executor for the current plan against this * call's sampled arguments: the single-encoder lowering on webgpu (async — @@ -566,16 +601,16 @@ class Pipeline { * @param {IKernelRunShortcut} shortcut - the user's kernel * @returns {IKernelRunShortcut} private clone */ - _cloneKernel(shortcut) { + _cloneKernel(shortcut, overrides) { const kernel = shortcut.kernel; - const settings = { + const settings = Object.assign({ output: Array.from(kernel.output), pipeline: true, immutable: true, // argument types can differ between plan positions of one kernel // (texture in the ping-pong seat, plain array from a pipeline arg) dynamicArguments: true, - }; + }, overrides || {}); const optional = ['constants', 'constantTypes', 'precision', 'loopMaxIterations', 'strictIntegers', 'fixIntegerDivisionAccuracy', 'optimizeFloatMemory', 'tactic', 'functions', 'nativeFunctions', 'injectedNative', 'debug', 'randomSeed', 'returnType']; // types the USER declared pin the clone exactly as they pin the kernel; // types inferred by a build must not -- the clone re-infers per plan @@ -601,8 +636,77 @@ class Pipeline { * @param {Array} args - sampled pipeline arguments * @returns {Promise<*>} */ + /** + * Array pipeline arguments upload ONCE per call on backends where an + * upload costs (GL textures, webgpu buffers): a lazy per-arg identity + * kernel parks the value device-side and every consuming step binds the + * handle -- feeding the raw array to a 200-step plan re-uploaded it 200 + * times, which was most of the remaining gap to hand-rolled ping-pong. + * cpu/webasm consume arrays natively, so there the raw value is optimal. + */ + _uploadArg(plan, index, value) { + const key = 'up:' + index; + let upload = plan.genericClones.get(key); + if (!upload) { + const dims = argDimensions(value); + const source = dims[2] > 1 ? + 'function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }' : + dims[1] > 1 ? + 'function (v) { return v[this.thread.y][this.thread.x]; }' : + 'function (v) { return v[this.thread.x]; }'; + const output = dims[2] > 1 ? [dims[0], dims[1], dims[2]] : dims[1] > 1 ? [dims[0], dims[1]] : [dims[0]]; + upload = this.gpu.createKernel(source, { output, pipeline: true, immutable: false }); + plan.genericClones.set(key, upload); + } + return upload(value); + } + async _executeGeneric(plan, args) { const slots = new Array(plan.buffers.length).fill(null); + // the clones are statically typed and the uploads statically shaped, so + // argument size drift rebuilds them (the fused executors' recompile + // contract); sizes re-derive from the current values on next use + if (!plan.genericArgDims) plan.genericArgDims = new Map(); + for (let i = 0; i < args.length; i++) { + const value = args[i]; + if (!value || typeof value !== 'object') continue; + // resident handles (textures, buffer results) size where they bind; + // only plain arrays and Inputs shape the clones and uploads + if (typeof value.toArray === 'function' && !(value instanceof Input)) continue; + const dims = argDimensions(value).join('x'); + const known = plan.genericArgDims.get(i); + if (known === undefined) { + plan.genericArgDims.set(i, dims); + } else if (known !== dims) { + const gpuKernels = this.gpu && this.gpu.kernels; + for (const clone of plan.genericClones.values()) { + if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) clone.destroy(); + } + plan.genericClones.clear(); + plan.genericArgDims = new Map([ + [i, dims] + ]); + break; + } + } + const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; + const uploadsPay = backendMode === 'gpu' || backendMode === 'webgpu'; + const uploaded = new Array(args.length).fill(null); + if (uploadsPay) { + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== 'pipelineArg' || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== 'object') continue; + if (typeof value.toArray === 'function' && !(value instanceof Input)) continue; // already resident + let handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === 'function') handle = await handle; + uploaded[binding.index] = handle; + } + } + } try { for (let i = 0; i < plan.steps.length; i++) { const step = plan.steps[i]; @@ -611,20 +715,21 @@ class Pipeline { for (let j = 0; j < bindings.length; j++) { const binding = bindings[j]; if (binding.source === 'pipelineArg') { - resolved[j] = args[binding.index]; + resolved[j] = uploaded[binding.index] || args[binding.index]; } else if (binding.source === 'step') { resolved[j] = slots[plan.steps[binding.step].outputBuffer]; } else { resolved[j] = binding.value; } } - let output = plan.kernels[step.kernel].clone.apply(null, resolved); + let output = this._genericClone(plan, step).apply(null, resolved); if (output && typeof output.then === 'function') { output = await output; } - // the slot's previous occupant is past its last read (assignBuffers - // guarantees it), so its texture can go before the new one parks - releaseValue(slots[step.outputBuffer]); + // no release: the mutable clone OWNS its output for the plan's life + // and re-renders it in place next parity -- the previous occupant is + // past its last read (assignBuffers guarantees it), and per-step + // texture churn was a 29x loss on GL ping-pong plans slots[step.outputBuffer] = output; } const results = plan.results; @@ -644,6 +749,10 @@ class Pipeline { if (value && typeof value.then === 'function') { value = await value; } + } else if (binding.source === 'step') { + // a cpu clone's mutable result is re-rendered in place by the next + // call; the caller's copy must be theirs to keep + value = copyPlainResult(value); } values[i] = value; } @@ -655,9 +764,8 @@ class Pipeline { } return shaped; } finally { - for (let i = 0; i < slots.length; i++) { - releaseValue(slots[i]); - } + // slot occupants are clone-owned; they die with the plan, not the call + slots.length = 0; } } @@ -681,6 +789,12 @@ class Pipeline { clone.destroy(); } } + for (const clone of this.plan.genericClones.values()) { + if (!gpuKernels || gpuKernels.indexOf(clone.kernel) !== -1) { + clone.destroy(); + } + } + this.plan.genericClones.clear(); if (this.plan.held) { releaseSnapshots(this.plan.held); } @@ -688,6 +802,20 @@ class Pipeline { } } +function argDimensions(value) { + const dims = value instanceof Input ? Array.from(value.size) : Array.from(utils.getDimensions(value)); + while (dims.length < 3) { + dims.push(1); + } + return dims; +} + +function copyPlainResult(value) { + if (ArrayBuffer.isView(value)) return value.slice(0); + if (Array.isArray(value)) return value.map(copyPlainResult); + return value; +} + function releaseValue(value) { if (value && typeof value.delete === 'function') { value.delete(); diff --git a/test/features/pipeline/correctness.js b/test/features/pipeline/correctness.js index 04316114..d6670abe 100644 --- a/test/features/pipeline/correctness.js +++ b/test/features/pipeline/correctness.js @@ -231,3 +231,32 @@ eachMode('2d output kernels', async (assert, mode, kind) => { assertClose(assert, result, [4, 8, 12, 16], 'fused run is correct'); await gpu.destroy(); }); + +test('generic executor survives argument size drift across calls headlessgl', async assert => { + if (!GPU.isHeadlessGLSupported) { assert.ok(true, 'no headlessgl'); return; } + // clones are statically typed and shaped since the mutable-clone rework; + // a size change must rebuild them, not compute on stale dimensions + const gpu = new GPU({ mode: 'headlessgl' }); + const k = gpu.createKernel(function (a) { + return a[this.thread.x] * 2; + }, { output: [4], dynamicOutput: true, dynamicArguments: true }); + const p = gpu.createPipeline(function (v) { return k(v); }); + assert.deepEqual(Array.from(await p([1, 2, 3, 4])), [2, 4, 6, 8]); + k.setOutput([6]); + p.setConstants({}); + assert.deepEqual(Array.from(await p([1, 2, 3, 4, 5, 6])), [2, 4, 6, 8, 10, 12], 'rebuilt for the new size'); + assert.deepEqual(Array.from(await p([6, 5, 4, 3, 2, 1])), [12, 10, 8, 6, 4, 2], 'steady after rebuild'); + await gpu.destroy(); +}); + +test('generic pipeline results are caller-owned, not clone-owned cpu', async assert => { + // mutable cpu clones re-render their arrays in place; a held result from + // call N must not change when call N+1 runs + const gpu = new GPU({ mode: 'cpu' }); + const k = gpu.createKernel(function (a) { return a[this.thread.x] + 1; }, { output: [3] }); + const p = gpu.createPipeline(function (v) { return k(v); }); + const first = await p([1, 2, 3]); + await p([10, 20, 30]); + assert.deepEqual(Array.from(first), [2, 3, 4], 'call N result survives call N+1'); + await gpu.destroy(); +}); From 358cdd9c417b98105237eaf389c33ad155de26d3 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 16:55:07 +0800 Subject: [PATCH 13/16] feat(pipeline): threads:false setting and an executed-backend accessor The two pre-merge asks from the benchmark integration review: a pipeline can pin the webasm lowering to its sync path (threads: false) so single-threaded benchmark columns stay comparable, and pipeline.backend reports the mode of the clones that actually execute -- under degradation it says 'cpu', restoring the silent-degradation safety net suites probe on kernels. The executor already consulted _threadsDisabled; the setting now reaches it (a later re-init in the constructor was clobbering it, caught by the pin test). Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 10 ++++++++-- dist/gpu-browser-core.min.js | 4 ++-- dist/gpu-browser.js | 10 ++++++++-- dist/gpu-browser.min.js | 4 ++-- src/gpu.js | 9 +++++++++ src/index.d.ts | 4 ++++ src/pipeline.js | 6 +++++- test/features/pipeline/lifecycle.js | 24 ++++++++++++++++++++++++ 8 files changed, 62 insertions(+), 9 deletions(-) diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 7f9d1a6a..e0994292 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -20369,12 +20369,12 @@ this.fn = fn; this.argumentCount = fn.length; this.constants = Object.assign({}, settings.constants || {}); + this._threadsDisabled = settings.threads === false; this.plan = null; this.executorKind = "generic"; this.fallbackReason = null; this._executor = void 0; this._fusionDisabled = false; - this._threadsDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -21146,6 +21146,12 @@ Object.defineProperty(shortcut, "plan", { get: () => pipeline.plan }); + Object.defineProperty(shortcut, "backend", { + get: () => { + if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; + return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + } + }); return shortcut; } createKernelMap() { diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index f128c2eb..2fe1624b 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>m(r),()=>m(r)),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}async _executeGeneric(e,t){const n=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===s||"webgpu"===s,a=new Array(t.length).fill(null);if(i)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>m(r),()=>m(r)),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}async _executeGeneric(e,t){const n=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===s||"webgpu"===s,a=new Array(t.length).fill(null);if(i)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),Object.defineProperty(n,"backend",{get:()=>r.plan&&0!==r.plan.kernels.length?r.plan.kernels[0].clone.kernel.constructor.mode:null}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index c6933a85..7cdd6473 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -24566,12 +24566,12 @@ this.fn = fn; this.argumentCount = fn.length; this.constants = Object.assign({}, settings.constants || {}); + this._threadsDisabled = settings.threads === false; this.plan = null; this.executorKind = "generic"; this.fallbackReason = null; this._executor = void 0; this._fusionDisabled = false; - this._threadsDisabled = false; this.destroyed = false; this._tail = Promise.resolve(); } @@ -25343,6 +25343,12 @@ Object.defineProperty(shortcut, "plan", { get: () => pipeline.plan }); + Object.defineProperty(shortcut, "backend", { + get: () => { + if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; + return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + } + }); return shortcut; } createKernelMap() { diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index f64ee56c..56fb5551 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:46:36 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>m(s),()=>m(s)),this._tail=r.then(b,b),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}async _executeGeneric(e,t){const r=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let r=0;r0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===n||"webgpu"===n,a=new Array(t.length).fill(null);if(i)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>m(s),()=>m(s)),this._tail=r.then(b,b),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}async _executeGeneric(e,t){const r=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let r=0;r0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===n||"webgpu"===n,a=new Array(t.length).fill(null);if(i)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>s.plan&&0!==s.plan.kernels.length?s.plan.kernels[0].clone.kernel.constructor.mode:null}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/gpu.js b/src/gpu.js index b9ccb8da..6e28b638 100644 --- a/src/gpu.js +++ b/src/gpu.js @@ -614,6 +614,15 @@ class GPU { Object.defineProperty(shortcut, 'plan', { get: () => pipeline.plan, }); + // the backend that actually EXECUTES: the plan clones', not the user + // kernels' -- under degradation the clone swaps to cpu and this says so, + // which is the silent-degradation safety net benchmark suites probe + Object.defineProperty(shortcut, 'backend', { + get: () => { + if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; + return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + }, + }); return shortcut; } diff --git a/src/index.d.ts b/src/index.d.ts index 8b419268..d2b2a7fd 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -410,6 +410,8 @@ export type PipelineFunction = (this: { constants: IConstantsThis }, ...args: IP IPipelineHandle | IPipelineHandle[] | { [key: string]: IPipelineHandle }; export interface IPipelineSettings { + /** false pins the webasm lowering to its sync path (no worker pool) */ + threads?: boolean; /** trace-time facts; change via setConstants, which re-traces on the next call */ constants?: IConstants; } @@ -429,6 +431,8 @@ export interface IPipeline { } export interface IPipelineRunShortcut { + /** the backend mode that actually executes the plan (the clones'), null before the first call */ + readonly backend: string | null; (...args: KernelVariable[]): Promise; pipeline: IPipeline; setConstants(constants: IConstants): this; diff --git a/src/pipeline.js b/src/pipeline.js index 926543cc..e35a811b 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -310,6 +310,11 @@ class Pipeline { this.fn = fn; this.argumentCount = fn.length; this.constants = Object.assign({}, settings.constants || {}); + // threads: false pins the webasm lowering to its sync path -- a + // benchmark comparing single-threaded columns needs the plan's win + // without the pool's (the fused-encoder and generic paths are + // unaffected; they were never threaded) + this._threadsDisabled = settings.threads === false; this.plan = null; /** * executor identity probe for tests and later phases: 'generic' executes @@ -336,7 +341,6 @@ class Pipeline { /** test/benchmark hook: forces the generic executor when true */ this._fusionDisabled = false; /** test/benchmark hook: keeps a fused executor off the worker pool */ - this._threadsDisabled = false; this.destroyed = false; /** * concurrent calls to one pipeline serialize on this tail, the same diff --git a/test/features/pipeline/lifecycle.js b/test/features/pipeline/lifecycle.js index bf98c306..be27e680 100644 --- a/test/features/pipeline/lifecycle.js +++ b/test/features/pipeline/lifecycle.js @@ -205,3 +205,27 @@ test('the user kernel is not observably reconfigured by pipeline use', async ass assert.ok(peak <= 3, `peak live intermediates bounded by the two plan buffers, saw ${ peak }`); gpu.destroy(); }); + +test('threads: false pins the webasm lowering to fused-sync', async assert => { + if (!GPU.isWebAssemblySupported || typeof SharedArrayBuffer === 'undefined') { assert.ok(true, 'no threads here anyway'); return; } + const gpu = new GPU({ mode: 'webasm' }); + const k = gpu.createKernel(function (a) { return a[this.thread.x] + 1; }, { output: [16384] }); + const threaded = gpu.createPipeline(function (v) { return k(v); }); + const pinned = gpu.createPipeline(function (v) { return k(v); }, { threads: false }); + const data = new Float32Array(16384).fill(3); + await threaded(data); + await pinned(data); + assert.equal(threaded.executorKind, 'fused-threaded', 'big plans thread by default'); + assert.equal(pinned.executorKind, 'fused-sync', 'threads: false keeps the plan single-threaded'); + await gpu.destroy(); +}); + +test('backend reports the executing clones\' mode, cpu', async assert => { + const gpu = new GPU({ mode: 'cpu' }); + const k = gpu.createKernel(function (a) { return a[this.thread.x] + 1; }, { output: [4] }); + const p = gpu.createPipeline(function (v) { return k(v); }); + assert.equal(p.backend, null, 'null before the first call builds the plan'); + await p([1, 2, 3, 4]); + assert.equal(p.backend, 'cpu'); + await gpu.destroy(); +}); From 2b1831802e15b70317cc83985b57e0cbc08765e8 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 17:15:06 +0800 Subject: [PATCH 14/16] fix(pipeline): backend derives from the executor; handle screens and eager uploads pipeline.backend read plan.kernels[0].clone -- exactly the reverse-engineered path the benchmark integration warned breaks silently, and 0d5b105 had already made it stale (the mutable genericClones execute, not the plan clones). It now derives from the executor that ran: fused kinds name their backend, generic reports its writer clones' mode, and under degradation-inside-generic it says 'cpu'. The introspection surface (backend, executorKind, fallbackReason, threads: false) is documented in the README as supported API. The webasm fused executor's per-call argument check never screened GPU-resident handles -- the webgpu review's finding applied there too and a texture argument crashed flattenTo instead of degrading; it now recompiles-then-degrades with the named reason, end to end (webasm fused -> generic -> clone falls to cpu -> backend says 'cpu'). Short plans' fixed per-call cost: when the pipeline is quiescent, GL argument uploads run synchronously at call time, so the upload texture IS the call-time snapshot and the deep copy is skipped (the copy+ flatten double work is gone; overlapped calls keep the copying path). Call-time sampling semantics pinned by test on both paths. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 9 +++ dist/gpu-browser-core.js | 53 ++++++++++++--- dist/gpu-browser-core.min.js | 4 +- dist/gpu-browser.js | 53 ++++++++++++--- dist/gpu-browser.min.js | 4 +- src/backend/web-assembly/pipeline-executor.js | 6 ++ src/gpu.js | 21 ++++-- src/pipeline.js | 66 ++++++++++++++++--- test/features/pipeline/lifecycle.js | 18 +++++ 9 files changed, 198 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index e779a0fc..eb7767bc 100644 --- a/README.md +++ b/README.md @@ -1391,6 +1391,15 @@ Calling a pipeline **always returns a Promise** — the [async contract](#asynch Every backend runs pipelines. The reference path (`executorKind: 'generic'`) walks the plan through the normal kernel machinery — private per-pipeline kernel instances with `pipeline: true` forced on, your kernel's settings never observably touched — so on GL it is textures end-to-end. On **webasm** the plan *fuses*: every step compiles over one shared `WebAssembly.Memory` laid out `[pipeline args | plan buffers]`, passes run back-to-back with intermediates never copied out between steps (`'fused-sync'`), and where wasm threads are available the worker pool executes the *whole plan* per worker with Atomics-based barriers between steps — one dispatch per pipeline call, no main-thread round trip per pass (`'fused-threaded'`). Anything the webasm backend cannot take degrades to the generic executor under its usual contract: the reason is queryable at `pipeline.fallbackReason`, and `pipeline.executorKind` tells you which executor actually ran. +### Reading what actually executed + +Introspection is **supported API**, not plan internals — it exists precisely so a correctness harness can assert the backend it asked for is the backend that ran (the guard that caught seventeen silent CPU degradations in #868): + +* `pipeline.executorKind` — `'fused-threaded'` / `'fused-sync'` (webasm), `'fused-encoder'` (webgpu), or `'generic'` (every backend, and the degradation target of the fused executors). +* `pipeline.backend` — the mode of the kernels that actually execute, derived from the executor that ran; under degradation it says `'cpu'`, exactly like `kernel.kernel.constructor.mode` does for kernels. +* `pipeline.fallbackReason` — why a fused executor declined this plan, `null` while fused. +* `createPipeline(fn, { threads: false })` pins the webasm lowering to its sync path, for callers (benchmarks, mainly) whose comparisons must stay single-threaded. + What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): **5.7× on heat threaded, 5.2× on jacobi** (heat 890 ms vs 5073 ms per-pass, jacobi 387 ms vs 1997 ms — and 2.8×/3.2× over plain JavaScript on rows the webasm backend previously lost), against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. Not in v1, stated plainly: diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index e0994292..c367cd6e 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -19544,6 +19544,7 @@ for (const [index, region] of this._argArrayRegions) { const value = args[index]; if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + if (typeof value.toArray === "function" && !(value instanceof Input)) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); const dims = valueDimensions(value); if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); } @@ -20370,6 +20371,7 @@ this.argumentCount = fn.length; this.constants = Object.assign({}, settings.constants || {}); this._threadsDisabled = settings.threads === false; + this._inFlight = 0; this.plan = null; this.executorKind = "generic"; this.fallbackReason = null; @@ -20382,7 +20384,10 @@ if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); const held = []; - for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); + let preUploaded = null; + if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); + for (let i = 0; i < args.length; i++) if (preUploaded && preUploaded[i]) sampled[i] = args[i]; else sampled[i] = snapshotValue(args[i], held); + this._inFlight++; const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { @@ -20406,9 +20411,13 @@ } } else this._degrade(e.message); } - return this._executeGeneric(this.plan, sampled); + return this._executeGeneric(this.plan, sampled, preUploaded); }); - if (held.length > 0) promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); + const settle = () => { + this._inFlight--; + if (held.length > 0) releaseSnapshots(held); + }; + promise.then(settle, settle); this._tail = promise.then(noop, noop); return promise; } @@ -20558,7 +20567,28 @@ } return upload(value); } - async _executeGeneric(plan, args) { + _genericEagerUploadsPay(plan) { + if (plan.kernels.length === 0) return false; + return plan.kernels[0].clone.kernel.constructor.mode === "gpu"; + } + _eagerUploads(plan, args) { + const uploaded = new Array(args.length).fill(null); + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== "pipelineArg" || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + const handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === "function") return null; + uploaded[binding.index] = handle; + } + } + return uploaded; + } + async _executeGeneric(plan, args, preUploaded) { const slots = new Array(plan.buffers.length).fill(null); if (!plan.genericArgDims) plan.genericArgDims = new Map; for (let i = 0; i < args.length; i++) { @@ -20577,8 +20607,8 @@ } const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; const uploadsPay = backendMode === "gpu" || backendMode === "webgpu"; - const uploaded = new Array(args.length).fill(null); - if (uploadsPay) for (let i = 0; i < plan.steps.length; i++) { + const uploaded = preUploaded || new Array(args.length).fill(null); + if (uploadsPay && !preUploaded) for (let i = 0; i < plan.steps.length; i++) { const bindings = plan.steps[i].argBindings; for (let j = 0; j < bindings.length; j++) { const binding = bindings[j]; @@ -21148,8 +21178,13 @@ }); Object.defineProperty(shortcut, "backend", { get: () => { - if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; - return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + const kind = pipeline.executorKind; + if (kind === "fused-sync" || kind === "fused-threaded") return "webasm"; + if (kind === "fused-encoder") return "webgpu"; + const plan = pipeline.plan; + if (!plan) return null; + for (const [key, clone] of plan.genericClones) if (key.indexOf("up:") !== 0) return clone.kernel.constructor.mode; + return plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; } }); return shortcut; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index 2fe1624b..c5d69476 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},R=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},G=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:R,onFunctionCall:G,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:R}=f(),{GLTextureFloat2D:G}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=G,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=G,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),G=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(G.subKernels){if(f){const t=G.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,G)};`)}else p.push(` const result = { result: ${a(e,G)} };`),f=!0;m===G.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,G)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,G.kernelArguments,[],d,c);if(t)return t;const r=u(e,G.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:R}=i,G=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:R});let M=[];if(d.setIndent(2),G.build.apply(G,t),M.push(d.toString()),d.reset(),G.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),G.run.apply(G,t),G.renderKernels?G.renderKernels():G.renderOutput&&G.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),G.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),G.renderOutput===G.renderTexture)if(d.reset(),G.renderKernels){const e=G.renderKernels(),t=d.getContextVariableName(G.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=G;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(G)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=R(),{utils:a}=i(),u=G(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=R();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Re(),{WebGL2KernelValueDynamicUnsignedInput:f}=Ge(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return r.length>0&&n.then(()=>m(r),()=>m(r)),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}async _executeGeneric(e,t){const n=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===s||"webgpu"===s,a=new Array(t.length).fill(null);if(i)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),Object.defineProperty(n,"backend",{get:()=>r.plan&&0!==r.plan.kernels.length?r.plan.kernels[0].clone.kernel.constructor.mode:null}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=R(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:G()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,n)}),i=()=>{this._inFlight--,r.length>0&&m(r)};return s.then(i,i),this._tail=s.then(b,b),s}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const n=new Array(t.length).fill(null);for(let s=0;s0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=n||new Array(t.length).fill(null);if(a&&!n)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),Object.defineProperty(n,"backend",{get:()=>{const e=r.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=r.plan;if(!t)return null;for(const[e,r]of t.genericClones)if(0!==e.indexOf("up:"))return r.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index 7cdd6473..18c0e75c 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -23741,6 +23741,7 @@ for (const [index, region] of this._argArrayRegions) { const value = args[index]; if (!value || typeof value !== "object") throw new FusionFallback(`pipeline argument ${index} is no longer an array`, true); + if (typeof value.toArray === "function" && !(value instanceof Input)) throw new FusionFallback(`pipeline argument ${index} is now a GPU-resident handle`, true); const dims = valueDimensions(value); if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) throw new FusionFallback(`pipeline argument ${index} changed size from [${region.dims.join(", ")}] to [${dims.join(", ")}]`, true); } @@ -24567,6 +24568,7 @@ this.argumentCount = fn.length; this.constants = Object.assign({}, settings.constants || {}); this._threadsDisabled = settings.threads === false; + this._inFlight = 0; this.plan = null; this.executorKind = "generic"; this.fallbackReason = null; @@ -24579,7 +24581,10 @@ if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); const held = []; - for (let i = 0; i < args.length; i++) sampled[i] = snapshotValue(args[i], held); + let preUploaded = null; + if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); + for (let i = 0; i < args.length; i++) if (preUploaded && preUploaded[i]) sampled[i] = args[i]; else sampled[i] = snapshotValue(args[i], held); + this._inFlight++; const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { @@ -24603,9 +24608,13 @@ } } else this._degrade(e.message); } - return this._executeGeneric(this.plan, sampled); + return this._executeGeneric(this.plan, sampled, preUploaded); }); - if (held.length > 0) promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); + const settle = () => { + this._inFlight--; + if (held.length > 0) releaseSnapshots(held); + }; + promise.then(settle, settle); this._tail = promise.then(noop, noop); return promise; } @@ -24755,7 +24764,28 @@ } return upload(value); } - async _executeGeneric(plan, args) { + _genericEagerUploadsPay(plan) { + if (plan.kernels.length === 0) return false; + return plan.kernels[0].clone.kernel.constructor.mode === "gpu"; + } + _eagerUploads(plan, args) { + const uploaded = new Array(args.length).fill(null); + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== "pipelineArg" || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== "object") continue; + if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + const handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === "function") return null; + uploaded[binding.index] = handle; + } + } + return uploaded; + } + async _executeGeneric(plan, args, preUploaded) { const slots = new Array(plan.buffers.length).fill(null); if (!plan.genericArgDims) plan.genericArgDims = new Map; for (let i = 0; i < args.length; i++) { @@ -24774,8 +24804,8 @@ } const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; const uploadsPay = backendMode === "gpu" || backendMode === "webgpu"; - const uploaded = new Array(args.length).fill(null); - if (uploadsPay) for (let i = 0; i < plan.steps.length; i++) { + const uploaded = preUploaded || new Array(args.length).fill(null); + if (uploadsPay && !preUploaded) for (let i = 0; i < plan.steps.length; i++) { const bindings = plan.steps[i].argBindings; for (let j = 0; j < bindings.length; j++) { const binding = bindings[j]; @@ -25345,8 +25375,13 @@ }); Object.defineProperty(shortcut, "backend", { get: () => { - if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; - return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + const kind = pipeline.executorKind; + if (kind === "fused-sync" || kind === "fused-threaded") return "webasm"; + if (kind === "fused-encoder") return "webgpu"; + const plan = pipeline.plan; + if (!plan) return null; + for (const [key, clone] of plan.genericClones) if (key.indexOf("up:") !== 0) return clone.kernel.constructor.mode; + return plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; } }); return shortcut; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index 56fb5551..c5655d54 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 16:54:01 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t)});return s.length>0&&r.then(()=>m(s),()=>m(s)),this._tail=r.then(b,b),r}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}async _executeGeneric(e,t){const r=new Array(e.buffers.length).fill(null);e.genericArgDims||(e.genericArgDims=new Map);for(let r=0;r0?e.kernels[0].clone.kernel.constructor.mode:null,i="gpu"===n||"webgpu"===n,a=new Array(t.length).fill(null);if(i)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>s.plan&&0!==s.plan.kernels.length?s.plan.kernels[0].clone.kernel.constructor.mode:null}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,r)}),i=()=>{this._inFlight--,s.length>0&&m(s)};return n.then(i,i),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const r=new Array(t.length).fill(null);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=r||new Array(t.length).fill(null);if(a&&!r)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>{const e=s.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=s.plan;if(!t)return null;for(const[e,s]of t.genericClones)if(0!==e.indexOf("up:"))return s.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/backend/web-assembly/pipeline-executor.js b/src/backend/web-assembly/pipeline-executor.js index 1757dff8..c462708a 100644 --- a/src/backend/web-assembly/pipeline-executor.js +++ b/src/backend/web-assembly/pipeline-executor.js @@ -512,6 +512,12 @@ class WebAssemblyPipelineExecutor { if (!value || typeof value !== 'object') { throw new FusionFallback(`pipeline argument ${ index } is no longer an array`, true); } + // a GPU-resident handle (a GL texture, a webgpu buffer result) has no + // bytes flattenTo can reach -- recompile declines it with its own + // named reason and the run lands on the generic executor + if (typeof value.toArray === 'function' && !(value instanceof Input)) { + throw new FusionFallback(`pipeline argument ${ index } is now a GPU-resident handle`, true); + } const dims = valueDimensions(value); if (dims[0] !== region.dims[0] || dims[1] !== region.dims[1] || dims[2] !== region.dims[2]) { throw new FusionFallback(`pipeline argument ${ index } changed size from [${ region.dims.join(', ') }] to [${ dims.join(', ') }]`, true); diff --git a/src/gpu.js b/src/gpu.js index 6e28b638..5476dcd8 100644 --- a/src/gpu.js +++ b/src/gpu.js @@ -614,13 +614,24 @@ class GPU { Object.defineProperty(shortcut, 'plan', { get: () => pipeline.plan, }); - // the backend that actually EXECUTES: the plan clones', not the user - // kernels' -- under degradation the clone swaps to cpu and this says so, - // which is the silent-degradation safety net benchmark suites probe + // the backend that actually EXECUTES, derived from the executor that + // ran -- never from plan internals, which reorganize between releases. + // Under degradation inside the generic executor the writer clones swap + // to cpu and this says so: the silent-degradation safety net suites + // probe on kernels (#868), as supported API. Object.defineProperty(shortcut, 'backend', { get: () => { - if (!pipeline.plan || pipeline.plan.kernels.length === 0) return null; - return pipeline.plan.kernels[0].clone.kernel.constructor.mode; + const kind = pipeline.executorKind; + if (kind === 'fused-sync' || kind === 'fused-threaded') return 'webasm'; + if (kind === 'fused-encoder') return 'webgpu'; + const plan = pipeline.plan; + if (!plan) return null; + for (const [key, clone] of plan.genericClones) { + if (key.indexOf('up:') !== 0) return clone.kernel.constructor.mode; + } + // built but no generic run yet: the plan clones' mode is the + // backend a run WOULD execute on + return plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; }, }); return shortcut; diff --git a/src/pipeline.js b/src/pipeline.js index e35a811b..9e5c589a 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -315,6 +315,9 @@ class Pipeline { // without the pool's (the fused-encoder and generic paths are // unaffected; they were never threaded) this._threadsDisabled = settings.threads === false; + // calls queued or executing on the tail; zero means the plan's upload + // textures are quiescent and an eager synchronous upload is safe + this._inFlight = 0; this.plan = null; /** * executor identity probe for tests and later phases: 'generic' executes @@ -359,9 +362,22 @@ class Pipeline { if (this.destroyed) return Promise.reject(new Error(MSG_DESTROYED)); const sampled = new Array(args.length); const held = []; + // quiescent fast path: with no call in flight, a GL upload runs + // synchronously RIGHT NOW, so the upload texture IS the call-time + // snapshot and the deep copy is skipped -- copying was a fixed ~30 ms + // per call on image-sized arguments, which dominated short plans + let preUploaded = null; + if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) { + preUploaded = this._eagerUploads(this.plan, args); + } for (let i = 0; i < args.length; i++) { - sampled[i] = snapshotValue(args[i], held); + if (preUploaded && preUploaded[i]) { + sampled[i] = args[i]; + } else { + sampled[i] = snapshotValue(args[i], held); + } } + this._inFlight++; const promise = this._tail.then(async () => { if (this.destroyed) throw new Error(MSG_DESTROYED); if (!this.plan) { @@ -397,12 +413,13 @@ class Pipeline { } } } - return this._executeGeneric(this.plan, sampled); + return this._executeGeneric(this.plan, sampled, preUploaded); }); - if (held.length > 0) { - // cloned texture snapshots live exactly as long as the call - promise.then(() => releaseSnapshots(held), () => releaseSnapshots(held)); - } + const settle = () => { + this._inFlight--; + if (held.length > 0) releaseSnapshots(held); + }; + promise.then(settle, settle); this._tail = promise.then(noop, noop); return promise; } @@ -665,7 +682,38 @@ class Pipeline { return upload(value); } - async _executeGeneric(plan, args) { + /** + * Eager uploads are only sound where the upload call is SYNCHRONOUS (the + * GL family): the texture materializes before user code can run again. + * webgpu uploads return promises, so its generic path keeps copies. + */ + _genericEagerUploadsPay(plan) { + if (plan.kernels.length === 0) return false; + return plan.kernels[0].clone.kernel.constructor.mode === 'gpu'; + } + + _eagerUploads(plan, args) { + const uploaded = new Array(args.length).fill(null); + for (let i = 0; i < plan.steps.length; i++) { + const bindings = plan.steps[i].argBindings; + for (let j = 0; j < bindings.length; j++) { + const binding = bindings[j]; + if (binding.source !== 'pipelineArg' || uploaded[binding.index]) continue; + const value = args[binding.index]; + if (!value || typeof value !== 'object') continue; + if (typeof value.toArray === 'function' && !(value instanceof Input)) continue; + const handle = this._uploadArg(plan, binding.index, value); + if (handle && typeof handle.then === 'function') { + // not synchronous after all: abandon the fast path for this call + return null; + } + uploaded[binding.index] = handle; + } + } + return uploaded; + } + + async _executeGeneric(plan, args, preUploaded) { const slots = new Array(plan.buffers.length).fill(null); // the clones are statically typed and the uploads statically shaped, so // argument size drift rebuilds them (the fused executors' recompile @@ -695,8 +743,8 @@ class Pipeline { } const backendMode = plan.kernels.length > 0 ? plan.kernels[0].clone.kernel.constructor.mode : null; const uploadsPay = backendMode === 'gpu' || backendMode === 'webgpu'; - const uploaded = new Array(args.length).fill(null); - if (uploadsPay) { + const uploaded = preUploaded || new Array(args.length).fill(null); + if (uploadsPay && !preUploaded) { for (let i = 0; i < plan.steps.length; i++) { const bindings = plan.steps[i].argBindings; for (let j = 0; j < bindings.length; j++) { diff --git a/test/features/pipeline/lifecycle.js b/test/features/pipeline/lifecycle.js index be27e680..6c140a11 100644 --- a/test/features/pipeline/lifecycle.js +++ b/test/features/pipeline/lifecycle.js @@ -229,3 +229,21 @@ test('backend reports the executing clones\' mode, cpu', async assert => { assert.equal(p.backend, 'cpu'); await gpu.destroy(); }); + +test('eager-upload fast path keeps call-time sampling headlessgl', async assert => { + if (!GPU.isHeadlessGLSupported) { assert.ok(true, 'no headlessgl'); return; } + const gpu = new GPU({ mode: 'headlessgl' }); + const k = gpu.createKernel(function (a) { return a[this.thread.x] + 1; }, { output: [4] }); + const p = gpu.createPipeline(function (v) { return k(v); }); + await p([1, 2, 3, 4]); // plan built; pipeline quiescent -> next call is eager + const data = new Float32Array([10, 20, 30, 40]); + const pending = p(data); + data.fill(0); // mutated between call and settlement + assert.deepEqual(Array.from(await pending), [11, 21, 31, 41], 'sampled at call, not at run'); + // overlapped calls take the copy path and sample independently + const a = p(new Float32Array([1, 1, 1, 1])); + const b = p(new Float32Array([2, 2, 2, 2])); + assert.deepEqual(Array.from(await a), [2, 2, 2, 2]); + assert.deepEqual(Array.from(await b), [3, 3, 3, 3]); + await gpu.destroy(); +}); From b85e21beddf42734e2a11afd4847fc67aca18621 Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 17:42:56 +0800 Subject: [PATCH 15/16] fix(pipeline): arm the eager-upload fast path -- it was dead code The quiescent fast path tested _executor === null, but the settled has-degraded-to-generic sentinel is FALSE, so eager uploads never engaged on any GL pipeline -- exactly the short-plan image rows the path was built for (the benchmark integration measured the residual scaling with the argument's OUTER element count: the per-call deep copy of an Array(2048)-of-rows, which the armed fast path skips). The sentinel is now pinned by test so a future change cannot re-deaden the path silently, and an eager upload declines on argument size drift (the tail rebuild owns that) instead of writing out of bounds into the previous size's upload kernel. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- dist/gpu-browser-core.js | 8 ++++++-- dist/gpu-browser-core.min.js | 4 ++-- dist/gpu-browser.js | 8 ++++++-- dist/gpu-browser.min.js | 4 ++-- src/pipeline.js | 14 +++++++++++++- test/features/pipeline/lifecycle.js | 3 +++ 6 files changed, 32 insertions(+), 9 deletions(-) diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index c367cd6e..547b665d 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -20385,7 +20385,7 @@ const sampled = new Array(args.length); const held = []; let preUploaded = null; - if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); + if (this._inFlight === 0 && this.plan && this._executor === false && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); for (let i = 0; i < args.length; i++) if (preUploaded && preUploaded[i]) sampled[i] = args[i]; else sampled[i] = snapshotValue(args[i], held); this._inFlight++; const promise = this._tail.then(async () => { @@ -20581,6 +20581,10 @@ const value = args[binding.index]; if (!value || typeof value !== "object") continue; if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + if (plan.genericArgDims) { + const known = plan.genericArgDims.get(binding.index); + if (known !== void 0 && known !== argDimensions(value).join("x")) return null; + } const handle = this._uploadArg(plan, binding.index, value); if (handle && typeof handle.then === "function") return null; uploaded[binding.index] = handle; diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index c5d69476..c94cc3f3 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,n)}),i=()=>{this._inFlight--,r.length>0&&m(r)};return s.then(i,i),this._tail=s.then(b,b),s}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const n=new Array(t.length).fill(null);for(let s=0;s0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=n||new Array(t.length).fill(null);if(a&&!n)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),Object.defineProperty(n,"backend",{get:()=>{const e=r.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=r.plan;if(!t)return null;for(const[e,r]of t.genericClones)if(0!==e.indexOf("up:"))return r.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function r(e){const t=new Array(e.length);for(let r=0;r{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,r)=>{try{t(e.apply(e,arguments))}catch(e){r(e)}})},e.getPixels=t=>{const{x:r,y:n}=e.output;return t?function(e,t,r){const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,r=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let n=0;n{t.exports={}}),n=e((e,t)=>{var r=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[r,n,s]=this.size;if(s){if(this.value.length!==r*n*s)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} * ${s} = ${n*r*s}`)}else if(n){if(this.value.length!==r*n)throw new Error(`Input size ${this.value.length} does not match ${r} * ${n} = ${n*r}`)}else if(this.value.length!==r)throw new Error(`Input size ${this.value.length} does not match ${r}`)}toArray(){const{utils:e}=i(),[t,r,n]=this.size;return n?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r,n):r?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,r):this.value}};t.exports={Input:r,input:function(e,t){return new r(e,t)}}}),s=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:r,dimensions:n,output:s,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!s)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=r,this.dimensions=n,this.output=s,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=r(),{Input:a}=n(),{Texture:o}=s(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),r=new Uint8Array(e);if(t[0]=3735928559,239===r[0])return"LE";if(222===r[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let r=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===r&&(r=[]),r},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e.isActiveClone=null,t[r]=c.clone(e[r]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[r,n,s]=t,i=(r||1)*(n||1)*(s||1);return e.optimizeFloatMemory&&"single"===e.precision&&(r=i=Math.ceil(i/4)),n>1&&r*n===i?new Int32Array([r,n]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let r=Math.ceil(t),n=Math.floor(t);for(;r*nMath.floor((e+t-1)/t)*t,getDimensions(e,t){let r;if(c.isArray(e)){const t=[];let n=e;for(;c.isArray(n);)t.push(n.length),n=n[0];r=t.reverse()}else if(e instanceof o)r=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);r=e.size}if(t)for(r=Array.from(r);r.length<3;)r.push(1);return new Int32Array(r)},flatten2dArrayTo(e,t){let r=0;for(let n=0;ne.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,r){r?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${r}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,r)=>{const n=r/2|0,s=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,r)=>{const n=new Array(r);for(let s=0;s{const s=new Array(n);for(let i=0;i{const r=new Float32Array(t);let n=0;for(let s=0;s{const n=new Array(r);let s=0;for(let i=0;i{const s=new Array(n);let i=0;for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=new Array(r),s=4*t;for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(t),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const r=new Array(e),n=4*t;let s=0;for(let t=0;t{const n=4*t,s=new Array(r);for(let i=0;i{const s=4*t,i=new Array(n);for(let a=0;a{const{findDependency:r,thisLookup:n,doNotDefine:s}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const r=[];for(let n=0;nnull!==e);return s.length<1?"":`${t.kind} ${s.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?n(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(r("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const n=r(t.callee.object.name,t.callee.property.name);return null===n?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(n),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?n(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const r=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${r}`;const n="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${r}${n} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let r=0;r{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let r=0;r{const r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[r(t),n(t),s(t),i(t)];return a.rKernel=r,a.gKernel=n,a.bKernel=s,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,r,n)=>{const s=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});s(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[r,n],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[s.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:r}=i(),{Input:s}=n();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!r.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?r.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const n=new Array(t.length);for(let s=0;st.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&s.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else s=t.argumentTypes||[];return{name:t.name||r.getFunctionNameFromString(n)||("function"==typeof e&&e.name?e.name:null),source:n,argumentTypes:s,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let n=0;n{t.exports={FunctionBuilder:class e{static fromKernel(t,r,n){const{kernelArguments:s,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:T,followingReturnStatement:S,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(s.length),E={};for(let e=0;eU.needsArgumentType(e,t),k=(e,t,r)=>{U.assignArgumentType(e,t,r)},L=(e,t,r)=>U.lookupReturnType(e,t,r),F=e=>U.lookupFunctionArgumentTypes(e),$=(e,t)=>U.lookupFunctionArgumentName(e,t),C=(e,t)=>U.lookupFunctionArgumentBitRatio(e,t),D=(e,t,r,n)=>{U.assignArgumentType(e,t,r,n)},G=(e,t,r,n)=>{U.assignArgumentBitRatio(e,t,r,n)},R=(e,t,r)=>{U.trackFunctionCall(e,t,r)},M=(e,t)=>{const n=[];for(let t=0;tnew r(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:L,lookupFunctionArgumentTypes:F,lookupFunctionArgumentName:$,lookupFunctionArgumentBitRatio:C,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:D,triggerImplyArgumentBitRatio:G,onFunctionCall:R,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:n}=e;return new r(n,Object.assign({},O,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const U=new e({kernel:t,rootNode:z,functionNodes:V,nativeFunctions:d,subKernelNodes:B});return U}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const r=t.indexOf(e);if(-1===r)t.push(e);else{const e=t.splice(r,1)[0];t.push(e)}return t}const r=this.functionMap[e];if(r){const n=t.indexOf(e);if(-1===n){t.push(e),r.toString();for(let e=0;e-1){t.push(this.nativeFunctions[s].source);continue}const i=this.functionMap[n];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let r=0;r0){const s=t.arguments;for(let t=0;t{const{utils:r}=i();function n(e){return e.length>0?e[e.length-1]:null}const s="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return n(this.functionContexts)}get currentContext(){return n(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:r}=this;for(const e in r)r.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=r[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=n(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(s),e(),this.trackedIdentifiers=null,this.popState(s),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:r,runningContexts:n}=this,s=t[e]||r[e]||null;if(!s&&t===r&&n.length>0){const t=n[n.length-2];if(t[e])return t[e]}return s}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=r.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,r=this.hasState(o),n={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:r,inForLoopTest:null,assignable:t===this.currentFunctionContext||!r&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=n),this.declarations.push(n),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const r=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in r)"@contextType"!==e&&t.indexOf(e)>-1&&(r[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(s)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const n=r(),{utils:s}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const r=[];for(let n=0;n{if(!e||"object"!=typeof e||r)return e;if(Array.isArray(e))return e.map(n);switch(e.type){case"ContinueStatement":return e.label?(r=!0,e):d({type:"BlockStatement",body:[...S(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=n(e.consequent),e.alternate&&(e.alternate=n(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(n),e;case"SwitchStatement":for(let t=0;t0?(r.push(e),r):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let r=0;r0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||n))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),r=t.body[0].declarations[0].init;if(f(r,this.requiresSequenceFreeForInit),this.traceFunctionAST(r),!t)throw new Error("Failed to parse JS code");return this.ast=r}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,r=this.argumentNames||[],n=s=>{if(s&&"object"==typeof s)if(Array.isArray(s))for(const e of s)n(e);else{"AssignmentExpression"===s.type&&"Identifier"===s.left.type&&-1!==r.indexOf(s.left.name)&&e.add(s.left.name),"UpdateExpression"===s.type&&"Identifier"===s.argument.type&&-1!==r.indexOf(s.argument.name)&&e.add(s.argument.name),"VariableDeclarator"===s.type&&"Identifier"===s.id.type&&-1!==r.indexOf(s.id.name)&&t.add(s.id.name);for(const e in s){if("loc"===e||"range"===e||"parent"===e)continue;const t=s[e];t&&"object"==typeof t&&n(t)}}};n(this.getJsAST());for(const r of t)e.delete(r);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:r,functions:n,identifiers:s,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=s,this.functionCalls=i,this.functions=n;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const r=this.getType(e.left);if(this.isState("skip-literal-correction"))return r;if("LiteralInteger"===r){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===r){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[r]||r;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let r;for(let e=0;ee.isSafe)}getDependencies(e,t,r){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let n=0;n-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,r);case"Identifier":const n=this.getDeclaration(e);if(n)t.push({name:e.name,origin:"declaration",isSafe:!r&&this.isSafeDependencies(n.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,r);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return r="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,r),this.getDependencies(e.right,t,r),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,r);case"VariableDeclaration":return this.getDependencies(e.declarations,t,r);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const s=this.getMemberExpressionDetails(e);switch(s.signature){case"value[]":this.getDependencies(e.object,t,r);break;case"value[][]":this.getDependencies(e.object.object,t,r);break;case"value[][][]":this.getDependencies(e.object.object.object,t,r);break;case"this.output.value":this.dynamicOutput&&t.push({name:s.name,origin:"output",isSafe:!1})}if(s)return s.property&&this.getDependencies(s.property,t,r),s.xProperty&&this.getDependencies(s.xProperty,t,r),s.yProperty&&this.getDependencies(s.yProperty,t,r),s.zProperty&&this.getDependencies(s.zProperty,t,r),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,r);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const r=[];for(;e;)e.computed?r.push("[]"):"ThisExpression"===e.type?r.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?r.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?r.unshift("."+e.property.name):r.unshift(t?"."+e.property.name:".value"):e.name?r.unshift(t?e.name:"value"):e.callee&&e.callee.name?r.unshift(t?e.callee.name+"()":"fn()"):e.elements?r.unshift("[]"):r.unshift("unknown"),e=e.object;const n=r.join("");return t||h.includes(n)?n:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let r=0;r0?n[n.length-1]:0;return new Error(`${e} on line ${n.length}, position ${i.length}:\n ${r}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",n.join(","),")"):t.push(n[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,r=null;const n=this.getVariableSignature(e);switch(n){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:n,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:n,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:n};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:n,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,r=this.getConstantType(t),!r)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:r,origin:"constants",signature:n,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:n,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const r=t[0];if("VariableDeclarator"===r.type&&r.id&&r.id.name&&r.id.name===e.name)return r;if(t.shift(),r.argument)t.push(r.argument);else if(r.body)t.push(r.body);else if(r.declarations)t.push(r.declarations);else if(Array.isArray(r))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let r=0;r{const{FunctionNode:r}=l();t.exports={CPUFunctionNode:class extends r{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(r)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let r=0;r0&&t.push(r.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=`safeI${this.astKey(e,"_")}`;return t.push(`let ${r} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${r} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");return r?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;r0&&t.push(",");const n=r[e],s=this.getDeclaration(n.id);s.valueType||(s.valueType=this.getType(n.init)),this.astGeneric(n,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:r,cases:n}=e;t.push("switch ("),this.astGeneric(r,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(n[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(n[e].consequent,t),n[e].consequent&&n[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:r,type:n,property:s,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(r){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(s){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(n){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,r;if("constants"===l){const t=this.constants[u];r="Input"===this.constantTypes[u],e=r?t.size:null}else r=this.isInput(u),e=r?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?r?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?r?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let r=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,r,e.arguments),t.push(r),t.push("(");const n=this.lookupFunctionArgumentTypes(r)||[];for(let s=0;s0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length,s=[];for(let t=0;t{const{utils:r}=i();t.exports={cpuKernelString:function(e,t){const n=[],s=[],i=[],a=!/^function/.test(e.color.toString());if(n.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const r=[];for(const n in t){if(!t.hasOwnProperty(n))continue;const s=t[n],i=e[n];switch(s){case"Number":case"Integer":case"Float":case"Boolean":r.push(`${n}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":r.push(`${n}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${r.join()} }`}(e.constants,e.constantTypes)};`),s.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){n.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),n.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=r.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=r.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});s.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[r].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),s.push(" _mediaTo2DArray,"),s.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=r.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),s.push(" _mediaTo2DArray,")}return`function(settings) {\n${n.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${s.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:n}=o(),{CPUFunctionNode:s}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends r{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${r}[x] = subKernelResult_${r};\n`:`result_${r}[x] = subKernelResult_${r};\n`)}this.followingReturnStatement=e.join("")}const e=n.fromKernel(this,s);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const r=t[0],n=t[1]||1;e.width=r,e.height=n,this._imageData=this.context.createImageData(r,n),this._colorData=new Uint8ClampedArray(r*n*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,r,n){void 0===n&&(n=1),e=Math.floor(255*e),t=Math.floor(255*t),r=Math.floor(255*r),n=Math.floor(255*n);const s=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*s;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=r,this._colorData[4*a+3]=n}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${n} === result_${e.name}`).join(" || ");t.push(`user_${n} === result${s?` || ${s}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,n=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(r);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e}setOutput(e){super.setOutput(e);const[t,r]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,r),this._colorData=new Uint8ClampedArray(t*r*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{const{Texture:r}=s();function n(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends r{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:r,kernel:s}=this;s.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),n(e,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const i=e.createTexture();n(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const r=e.createTexture();n(e,r),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),r._refs=1,this.texture=r}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();n(e,t);const r=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,r[0],r[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),n(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),f=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureFloat:class extends n{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const r=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,r),r}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return r.erectFloat(this.renderValues(),this.output[0])}}}}),m=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),g=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray2Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return r.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),x=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erectArray3(this.renderValues(),this.output[0])}}}}),b=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),v=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray3Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return r.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erectArray4(this.renderValues(),this.output[0])}}}}),S=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),A=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureArray4Float3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return r.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),w=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat2D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),_=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureFloat3D:class extends n{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return r.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),E=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),I=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized2D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),k=e((e,t)=>{const{utils:r}=i(),{GLTextureFloat:n}=f();t.exports={GLTextureMemoryOptimized3D:class extends n{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return r.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:r}=i(),{GLTexture:n}=d();t.exports={GLTextureUnsigned:class extends n{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return r.erectPackedFloat(this.renderValues(),this.output[0])}}}}),F=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned2D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),$=e((e,t)=>{const{utils:r}=i(),{GLTextureUnsigned:n}=L();t.exports={GLTextureUnsigned3D:class extends n{constructor(e){super(e),this.type="NumberTexture"}toArray(){return r.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),C=e((e,t)=>{const{GLTextureUnsigned:r}=L();t.exports={GLTextureGraphical:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),D=e((e,t)=>{const{Kernel:r}=a(),{utils:n}=i(),{GLTextureArray2Float:s}=m(),{GLTextureArray2Float2D:o}=g(),{GLTextureArray2Float3D:u}=y(),{GLTextureArray3Float:l}=x(),{GLTextureArray3Float2D:h}=b(),{GLTextureArray3Float3D:c}=v(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=S(),{GLTextureArray4Float3D:D}=A(),{GLTextureFloat:G}=f(),{GLTextureFloat2D:R}=w(),{GLTextureFloat3D:M}=_(),{GLTextureMemoryOptimized:O}=E(),{GLTextureMemoryOptimized2D:N}=I(),{GLTextureMemoryOptimized3D:z}=k(),{GLTextureUnsigned:V}=L(),{GLTextureUnsigned2D:B}=F(),{GLTextureUnsigned3D:U}=$(),{GLTextureGraphical:K}=C();const P={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends r{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),2===r[0]&&1511===r[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const r=e.renderOutput();return e.destroy(!0),0===Math.round(r[0])&&1===Math.round(r[1])&&2===Math.round(r[2])&&3===Math.round(r[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return n.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],r=[],n=[],s=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?n[n.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){n.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){n.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){n.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){n.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!s.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(n.pop(),r.push(o),t.push(P[u]))}a++}else n.push("FUNCTION_ARGUMENTS"),a++;else n.pop(),a++;else n.push("COMMENT"),a+=2;else n.pop(),a+=2;else n.push("MULTI_LINE_COMMENT"),a+=2}if(n.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:r,argumentTypes:t}}static nativeFunctionReturnType(e){return P[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:r,context:s,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=r[0],t=Math.ceil(r[1]/4);a=new Float32Array(e*t*4*4),s.readPixels(0,0,e,4*t,s.RGBA,s.FLOAT,a)}else{const e=new Uint8Array(r[0]*r[1]*4);s.readPixels(0,0,r[0],r[1],s.RGBA,s.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?n.splitArray(a,t.output[0]):3===t.output.length?n.splitArray(a,t.output[0]*t.output[1]).map(function(e){return n.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=K,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=U,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=V,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=U,this.formatValues=n.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=n.erect2DPackedFloat,null):(this.TextureConstructor=V,this.formatValues=n.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=O,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=R,null):(this.TextureConstructor=G,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=s,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,this.formatValues=n.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=n.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=O,this.formatValues=n.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=n.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=R,this.formatValues=n.erect2DFloat,null):(this.TextureConstructor=G,this.formatValues=n.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=n.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=n.erect2DArray2,null):(this.TextureConstructor=s,this.formatValues=n.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=n.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=n.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=n.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=D,this.formatValues=n.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=n.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=n.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return n.linesToString(this.getMainResultKernelNumberTexture())+n.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return n.linesToString(this.getMainResultKernelArray2Texture())+n.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return n.linesToString(this.getMainResultKernelArray3Texture())+n.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return n.linesToString(this.getMainResultKernelArray4Texture())+n.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,r=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,r),r}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n*4);return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,s),s}getPixels(e){const{context:t,output:r}=this,[s,i]=r,a=new Uint8Array(s*i*4);t.readPixels(0,0,s,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:n.flipPixels(a,s,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:r}=this;for(let n=0;n{const{utils:r}=i(),{FunctionNode:n}=l(),s={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function r(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(r);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1}return function e(n){if(n&&"object"==typeof n&&!t)if(Array.isArray(n))n.forEach(e);else if("MemberExpression"===n.type&&n.computed&&r(n.property))t=!0;else for(const t in n)"loc"!==t&&"range"!==t&&"parent"!==t&&e(n[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&u(e[r],t))return!0;return!1}function h(e){let t=!1;return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("CallExpression"===r.type&&"Identifier"===r.callee.type&&r.arguments.some(e=>u(e,r.callee.name)))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(r){if(!r||"object"!=typeof r)return!0;if(Array.isArray(r))return r.every(e);if("string"==typeof r.type){if("UpdateExpression"===r.type||"SequenceExpression"===r.type)return!1;if("AssignmentExpression"===r.type&&r!==t)return!1}for(const t in r)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(r[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends n{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);return null===r&&null===n?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:r}=this;if(r){const e=d[r];if(!e)throw new Error(`unknown type ${r}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let n=0;n0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(s)];if(!i)throw this.astErrorOutput(`Unknown argument ${s} type`,e);"LiteralInteger"===i&&(this.argumentTypes[n]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=r.sanitizeName(s);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let n=0;n>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const r={"~":"bitwiseNot"}[e.operator];if(!r)return null;switch(t.push(r),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=r.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const r=this.argumentNames.indexOf(e),n=-1===r?null:d[this.argumentTypes[r]];if("float"===n||"int"===n||"bool"===n)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,r),r.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&r.has(t)},a=e=>{if(e&&"object"==typeof e&&!s)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&n.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))s=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))s=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&a(r)}};return a(e.body),!s&&e.test&&a(e.test),s}emitForParts(e,t){const{initArr:r,testArr:n,updateArr:s,bodyArr:i,isSafe:a}=e;if(a){const e=r.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${n.join("")};${s.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");r.length>0&&t.push(r.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${n.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (int ${r}=0;${r}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const r=this.isState("assignment-as-statement");if(r?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const r=this.getType(e.left),n=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==r&&"Integer"===n?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===r&&"LiteralInteger"===n?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return r||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let r=0;rnull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const r=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:r(e.consequent),alternate:r(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(r)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(r)}))}}};return e.map(r)},p=[];"DoWhileStatement"===t?(p.push(...n?c(l,()=>[a(i(n))]):l),n&&p.push(a(n))):(n&&p.push(a(n)),p.push(...s?c(l,()=>[u(i(s))]):l),s&&p.push(u(s)));const d={type:"BlockStatement",body:[...r?[u(r)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t])}};r(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let r=!1,n=this.linearTempId||0;const s=e=>({type:"Identifier",name:e}),i=(e,t,r)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:s(t),init:r}]}),o=(e,t)=>{const r="hoistSeq"+n++;return e.push(i("const",r,t)),s(r)},l=e=>!a(e),h=(e,t)=>{if(r||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const r=h(e.object,t),n=e.computed?h(e.property,t):e.property;return{...e,object:r,property:n}}case"CallExpression":{const r=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let n=0;nh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return r=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const n=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),n}case"AssignmentExpression":{if("Identifier"!==e.left.type)return r=!0,e;const n=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:n}}),o(t,e.left)}case"SequenceExpression":for(let r=0;r({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),s(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const r=h(e.left,t),a="hoistSeq"+n++;t.push(i("let",a,r));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:s(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?s(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:s(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),s(a)}default:return r=!0,e}};switch(e.type){case"ExpressionStatement":{const r=e.expression;if("AssignmentExpression"===r.type&&"Identifier"===r.left.type){const e=h(r.right,t);t.push({type:"ExpressionStatement",expression:{...r,right:e}})}else{const e=h(r,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let r=0;r{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const r=this.hoistedIndexReads,n=this.hoistedIndexReads=[],s=[];return this.astGeneric(e,s),this.hoistedIndexReads=r,t.push(...n,...s),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const n=e.declarations;if(!n||!n[0]||!n[0].init)throw this.astErrorOutput("Unexpected expression",e);const s=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),s.push(a.join(";")),t.push(s.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const r=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;er+1){u=!0,this.astSwitchCaseConsequent(n[r].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[r].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:n,name:s,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==s&&"y"!==s&&"z"!==s)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${s}`),t;case"this.output.value":if(this.dynamicOutput)switch(s){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(s){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[s]),t;const i=r.sanitizeName(s);switch(n){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${r.sanitizeName(s)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;case"fn()[][]":{const r=e.object.property,n=e.property,s=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!s||i(r)&&i(n)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t):(t.push(`getMatrix${s}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(n)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(n)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${r.sanitizeName(s)}`),t}const c=`${a}_${r.sanitizeName(s)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,s):this.constantBitRatios[s];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let n=null;const s=this.isAstMathFunction(e);if(n=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!n)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(n){case"pow":n="_pow";break;case"round":n="_round"}if(this.calledFunctions.indexOf(n)<0&&this.calledFunctions.push(n),"random"===n&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===s)this.castValueToFloat(n,t);else this.astGeneric(n,t)}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${r.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,n,i);const s=r.sanitizeName(a.name);t.push(`user_${s},user_${s}Size,user_${s}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const r=this.getType(e),n=e.elements.length;switch(r){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${n}(`);break;default:t.push(`vec${n}(`)}for(let r=0;r0&&t.push(", ");const n=e.elements[r];this.astGeneric(n,t)}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const n=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(n)){const e=`hoisted_${this.hoistedIndexReads.length}_${r.sanitizeName(this.name)}`,t=n.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${n};\n`),e}return n}}}}),R=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),M=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),N=e((e,t)=>{function r(e,t={}){const{contextName:r="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return T;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${r}.getError() !== ${r}.NONE) throw new Error('error');`):u.push(`${g}${r}.getError();`),e.getError();case"getExtension":{const t=`${r}Variables${d.length}`;u.push(`${g}const ${t} = ${r}.getExtension('${arguments[0]}');`);const s=e.getExtension(arguments[0]);if(s&&"object"==typeof s){const e=n(s,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),s}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${r}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${r}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${r}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${r}.drawBuffers([${s(arguments[0],{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${r}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?r+"."+t:e}function T(e){g=" ".repeat(e)}function S(e,t){const n=`${r}Variable${d.length}`;return u.push(`${g}const ${n} = ${t};`),d.push(e),n}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${r}.getError();\n${g}if (error !== ${r}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${r}[name] === error) {\n${g} throw new Error('${r} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${r}.${e}(${s(t,{contextName:r,contextVariables:d,getEntity:v,addVariable:S,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${r}Variable${t}`:null}}function n(e,t){const r=new Proxy(e,{get:function(t,r){return"function"==typeof t[r]?function(){if("drawBuffersWEBGL"===r)return h.push(`${p}${a}.drawBuffersWEBGL([${s(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[r].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(r,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(r,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(r,arguments)};`),o.push(t)}return t}:(n[e[r]]=r,e[r])}}),n={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return r;function f(e){return n.hasOwnProperty(e)?`${a}.${n[e]}`:u(e)}function m(e,t){return`${a}.${e}(${s(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const r=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${r} = ${t};`),r}}function s(e,t){const{variables:r,onUnrecognizedArgumentLookup:n}=t;return Array.from(e).map(e=>{const s=function(e){if(r)for(const t in r)if(r.hasOwnProperty(t)&&r[t]===e)return t;return n?n(e):null}(e);return s||function(e,t){const{contextName:r,contextVariables:n,getEntity:s,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=n.indexOf(e);if(o>-1)return`${r}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),r=/'/.test(e),n=/"/.test(e);return t?"`"+e+"`":r&&!n?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return s(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:r,glExtensionWiretap:n}),"undefined"!=typeof window&&(r.glExtensionWiretap=n,window.glWiretap=r)}),z=e((e,t)=>{const{glWiretap:r}=N(),{utils:n}=i();function s(e){let t=e.toString().replace(/^function /,"");const r=t.indexOf("=>");if(-1!==r&&!/[{]|\bfunction\b/.test(t.slice(0,r))){const e=t.slice(0,r).trim(),n=t.slice(r+2).trim();t=n.startsWith("{")?`${e} ${n}`:`${e} { return ${n}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const r="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${r}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${r}, ${t.output[0]})`}function o(e,t){const r=e.toArray.toString(),s=!/^function/.test(r);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${n.flattenFunctionToString(`${s?"function ":""}${r}`,{findDependency:(t,r)=>{if("utils"===t)return`const ${r} = ${n[r].toString()};`;if("this"===t)return"framebuffer"===r?"":`${s?"function ":""}${e[r].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(r,n)=>{if("texture"===r)return t;if("context"===r)return n?null:"gl";if(e.hasOwnProperty(r))return JSON.stringify(e[r]);throw new Error(`unhandled thisLookup ${r}`)}})}\n return toArray();\n }`}function u(e,t,r,n,s){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let s=0;s{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=r(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(R.subKernels){if(f){const t=R.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,R)};`)}else p.push(` const result = { result: ${a(e,R)} };`),f=!0;m===R.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,R)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,R.kernelArguments,[],d,c);if(t)return t;const r=u(e,R.kernelConstants,S?Object.keys(S).map(e=>S[e]):[],d,c);return r||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,kernelArguments:C,kernelConstants:D,tactic:G}=i,R=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:T,constants:S,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:L,argumentTypes:F,constantTypes:$,tactic:G});let M=[];if(d.setIndent(2),R.build.apply(R,t),M.push(d.toString()),d.reset(),R.kernelArguments.forEach((e,r)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let n=0;ne.varName).join(", ")}) {`),d.setIndent(4),R.run.apply(R,t),R.renderKernels?R.renderKernels():R.renderOutput&&R.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),R.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),R.renderOutput===R.renderTexture)if(d.reset(),R.renderKernels){const e=R.renderKernels(),t=d.getContextVariableName(R.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:r,mappedTextures:n}=R;for(let t=0;t"utils"===e?`const ${t} = ${n[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(R)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let O=[];return D.forEach(e=>{O.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${O.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),V=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:r,kernel:n,context:s,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!r)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=r,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${r}`:r,this.kernel=n,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=s,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),B=e((e,t)=>{const{utils:r}=i(),{KernelValue:n}=V();t.exports={WebGLKernelValue:class extends n{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${r.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueBoolean:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueFloat:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${r.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),P=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValue:n}=B();t.exports={WebGLKernelValueInteger:class extends n{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{WebGLKernelValue:r}=B(),{Input:s}=n();t.exports={WebGLKernelArray:class extends r{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:r}=this.kernel.constructor.features;if(e>r||t>r)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${r} for your GPU`):e{const{utils:r}=i(),{WebGLKernelArray:n}=W();function s(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends n{constructor(e,t){super(e,t);const{width:r,height:n}=s(e);this.checkSize(r,n),this.dimensions=[r,n,1],this.textureSize=[r,n],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:s}}),q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n,mediaSize:s}=j();t.exports={WebGLKernelValueDynamicHTMLImage:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=s(e);this.checkSize(t,r),this.dimensions=[t,r,1],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),X=e((e,t)=>{const{WebGLKernelValueHTMLImage:r}=j();t.exports={WebGLKernelValueHTMLVideo:class extends r{}}}),H=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:r}=q();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends r{}}}),Y=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=4;let[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Z=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGLKernelValueDynamicSingleInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),J=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedInput:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[n,s,i]=e.size;this.dimensions=new Int32Array([n||1,s||1,i||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;r.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Q=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),s="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W(),{sameError:s}=ee();t.exports={WebGLKernelValueNumberTexture:class extends n{constructor(e,t){super(e,t);const[r,n]=e.size;this.checkSize(r,n);const{size:s,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=s,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:r}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(s);if(t.mappedTextures){const{mappedTextures:r}=t;for(let t=0;t{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),se=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGLKernelValueDynamicSingleArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ae=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray1DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray2DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),le=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),he=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueSingleArray3DI:class extends n{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=r.getDimensions(e,!0);this.textureSize=r.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return r.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),pe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray2:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray3:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:r}=B();t.exports={WebGLKernelValueArray4:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGLKernelValueUnsignedArray:class extends n{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return r.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ye=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U(),{WebGLKernelValueFloat:n}=K(),{WebGLKernelValueInteger:s}=P(),{WebGLKernelValueHTMLImage:i}=j(),{WebGLKernelValueDynamicHTMLImage:a}=q(),{WebGLKernelValueHTMLVideo:o}=X(),{WebGLKernelValueDynamicHTMLVideo:u}=H(),{WebGLKernelValueSingleInput:l}=Y(),{WebGLKernelValueDynamicSingleInput:h}=Z(),{WebGLKernelValueUnsignedInput:c}=J(),{WebGLKernelValueDynamicUnsignedInput:p}=Q(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=ee(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=te(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=se(),{WebGLKernelValueDynamicSingleArray:x}=ie(),{WebGLKernelValueSingleArray1DI:b}=ae(),{WebGLKernelValueDynamicSingleArray1DI:v}=oe(),{WebGLKernelValueSingleArray2DI:T}=ue(),{WebGLKernelValueDynamicSingleArray2DI:S}=le(),{WebGLKernelValueSingleArray3DI:A}=he(),{WebGLKernelValueDynamicSingleArray3DI:w}=ce(),{WebGLKernelValueArray2:_}=pe(),{WebGLKernelValueArray3:E}=de(),{WebGLKernelValueArray4:I}=fe(),{WebGLKernelValueUnsignedArray:k}=me(),{WebGLKernelValueDynamicUnsignedArray:L}=ge(),F={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:L,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:r,Float:n,Integer:s,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=F[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]},kernelValueMaps:F}}),xe=e((e,t)=>{const{GLKernel:r}=D(),{FunctionBuilder:n}=o(),{WebGLFunctionNode:s}=G(),{utils:a}=i(),u=R(),{fragmentShader:l}=M(),{vertexShader:h}=O(),{glKernelString:c}=z(),{lookupKernelValueType:p}=ye();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends r{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return p(e,t,r,n)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:r}=this;if("string"==typeof r)for(let e=0;ee===n.name)&&t.push(n)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let r=b.indexOf(t);-1===r&&(r=b.length,b.push(t),v[r]=[e[0],e[1]]),this.maxTexSize=v[r]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:r}=this;let n=0;const s=()=>this.createTexture(),i=()=>this.constantTextureCount+n++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>r.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let n=0;nthis.createTexture(),onRequestIndex:()=>n++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[s]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:r,canvas:n}=this;r.enable(r.SCISSOR_TEST),this.pipeline&&this.precision,r.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),n.width=this.maxTexSize[0],n.height=this.maxTexSize[1];const s=this.threadDim=Array.from(this.output);for(;s.length<3;)s.push(1);const i=this.getVertexShader(arguments),a=r.createShader(r.VERTEX_SHADER);r.shaderSource(a,i),r.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=r.createShader(r.FRAGMENT_SHADER);if(r.shaderSource(u,o),r.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!r.getShaderParameter(a,r.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+r.getShaderInfoLog(a));if(!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+r.getShaderInfoLog(u));const l=this.program=r.createProgram();r.attachShader(l,a),r.attachShader(l,u),r.linkProgram(l),this.framebuffer=r.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?r.bindBuffer(r.ARRAY_BUFFER,d):(d=this.buffer=r.createBuffer(),r.bindBuffer(r.ARRAY_BUFFER,d),r.bufferData(r.ARRAY_BUFFER,h.byteLength+c.byteLength,r.STATIC_DRAW)),r.bufferSubData(r.ARRAY_BUFFER,0,h),r.bufferSubData(r.ARRAY_BUFFER,p,c);const f=r.getAttribLocation(this.program,"aPos");-1!==f&&(r.enableVertexAttribArray(f),r.vertexAttribPointer(f,2,r.FLOAT,!1,0,0));const m=r.getAttribLocation(this.program,"aTexCoord");-1!==m&&(r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,p)),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer);let g=0;r.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=n.fromKernel(this,s,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:r}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${r[0]}, ${r[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:r}=this;for(let n=0;n{if(t.hasOwnProperty(r))return t[r];throw`unhandled artifact ${r}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(r,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=n.fromKernel(this,s).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),be=e((e,t)=>{const n=r(),{WebGLKernel:s}=xe(),{glKernelString:i}=z();let a=null,o=null,u=null,l=null,h=null;t.exports={HeadlessGLKernel:class extends s{static get isSupported(){return null!==a||(this.setupFeatureChecks(),a=null!==u),a}static setupFeatureChecks(){if(o=null,l=null,"function"==typeof n)try{if(u=n(2,2,{preserveDrawingBuffer:!0}),!u||!u.getExtension)return;l={STACKGL_resize_drawingbuffer:u.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:u.getExtension("STACKGL_destroy_context"),OES_texture_float:u.getExtension("OES_texture_float"),OES_texture_float_linear:u.getExtension("OES_texture_float_linear"),OES_element_index_uint:u.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:u.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:u.getExtension("WEBGL_color_buffer_float")},h=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(l.OES_texture_float)}static getIsDrawBuffers(){return Boolean(l.WEBGL_draw_buffers)}static getChannelCount(){return l.WEBGL_draw_buffers?u.getParameter(l.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return u.getParameter(u.MAX_TEXTURE_SIZE)}static get testCanvas(){return o}static get testContext(){return u}static get features(){return h}initCanvas(){return{}}initContext(){return n(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return i(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),ve=e((e,t)=>{const{utils:r}=i(),{WebGLFunctionNode:n}=G();t.exports={WebGL2FunctionNode:class extends n{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===n)if(this.argumentNames.indexOf(s)>-1){const r=this.markupUserName(e.name);t.push(r.startsWith("cellShadow_")?r:`bool(${r})`)}else t.push(`user_${s}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Se=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),Ae=e((e,t)=>{const{WebGLKernelValueBoolean:r}=U();t.exports={WebGL2KernelValueBoolean:class extends r{}}}),we=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueFloat:n}=K();t.exports={WebGL2KernelValueFloat:class extends n{}}}),_e=e((e,t)=>{const{WebGLKernelValueInteger:r}=P();t.exports={WebGL2KernelValueInteger:class extends r{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ee=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueHTMLImage:n}=j();t.exports={WebGL2KernelValueHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Ie=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicHTMLImage:n}=q();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),ke=e((e,t)=>{const{utils:r}=i(),{WebGLKernelArray:n}=W();t.exports={WebGL2KernelValueHTMLImageArray:class extends n{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let r=0;r{const{utils:r}=i(),{WebGL2KernelValueHTMLImageArray:n}=ke();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:r}=e[0];this.checkSize(t,r),this.dimensions=[t,r,e.length],this.textureSize=[t,r],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Fe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueHTMLImage:n}=Ee();t.exports={WebGL2KernelValueHTMLVideo:class extends n{}}}),$e=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueDynamicHTMLImage:n}=Ie();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends n{}}}),Ce=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleInput:n}=Y();t.exports={WebGL2KernelValueSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;r.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),De=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleInput:n}=Ce();t.exports={WebGL2KernelValueDynamicSingleInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,n,s]=e.size;this.dimensions=new Int32Array([t||1,n||1,s||1]),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ge=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedInput:n}=J();t.exports={WebGL2KernelValueUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Re=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedInput:n}=Q();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Me=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:n}=ee();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:n}=te();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends n{getSource(){return r.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ne=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueNumberTexture:n}=re();t.exports={WebGL2KernelValueNumberTexture:class extends n{getSource(){const{id:e,sizeId:t,textureSize:n,dimensionsId:s,dimensions:i}=this,a=this.getVariablePrecisionString();return r.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${n[0]}, ${n[1]})`,`${a} ivec3 ${s} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicNumberTexture:n}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray:n}=se();t.exports={WebGL2KernelValueSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!r.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Be=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray:n}=Ve();t.exports={WebGL2KernelValueDynamicSingleArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=r.getDimensions(e,!0),this.textureSize=r.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray1DI:n}=ae();t.exports={WebGL2KernelValueSingleArray1DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray1DI:n}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Pe=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray2DI:n}=ue();t.exports={WebGL2KernelValueSingleArray2DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),We=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray2DI:n}=Pe();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueSingleArray3DI:n}=he();t.exports={WebGL2KernelValueSingleArray3DI:class extends n{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;r.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),qe=e((e,t)=>{const{utils:r}=i(),{WebGL2KernelValueSingleArray3DI:n}=je();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Xe=e((e,t)=>{const{WebGLKernelValueArray2:r}=pe();t.exports={WebGL2KernelValueArray2:class extends r{}}}),He=e((e,t)=>{const{WebGLKernelValueArray3:r}=de();t.exports={WebGL2KernelValueArray3:class extends r{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray4:r}=fe();t.exports={WebGL2KernelValueArray4:class extends r{}}}),Ze=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueUnsignedArray:n}=me();t.exports={WebGL2KernelValueUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Je=e((e,t)=>{const{utils:r}=i(),{WebGLKernelValueDynamicUnsignedArray:n}=ge();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends n{getSource(){const e=this.getVariablePrecisionString();return r.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Qe=e((e,t)=>{const{WebGL2KernelValueBoolean:r}=Ae(),{WebGL2KernelValueFloat:n}=we(),{WebGL2KernelValueInteger:s}=_e(),{WebGL2KernelValueHTMLImage:i}=Ee(),{WebGL2KernelValueDynamicHTMLImage:a}=Ie(),{WebGL2KernelValueHTMLImageArray:o}=ke(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=Fe(),{WebGL2KernelValueDynamicHTMLVideo:h}=$e(),{WebGL2KernelValueSingleInput:c}=Ce(),{WebGL2KernelValueDynamicSingleInput:p}=De(),{WebGL2KernelValueUnsignedInput:d}=Ge(),{WebGL2KernelValueDynamicUnsignedInput:f}=Re(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Me(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ne(),{WebGL2KernelValueDynamicNumberTexture:x}=ze(),{WebGL2KernelValueSingleArray:b}=Ve(),{WebGL2KernelValueDynamicSingleArray:v}=Be(),{WebGL2KernelValueSingleArray1DI:T}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:S}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=Pe(),{WebGL2KernelValueDynamicSingleArray2DI:w}=We(),{WebGL2KernelValueSingleArray3DI:_}=je(),{WebGL2KernelValueDynamicSingleArray3DI:E}=qe(),{WebGL2KernelValueArray2:I}=Xe(),{WebGL2KernelValueArray3:k}=He(),{WebGL2KernelValueArray4:L}=Ye(),{WebGL2KernelValueUnsignedArray:F}=Ze(),{WebGL2KernelValueDynamicUnsignedArray:$}=Je(),C={unsigned:{dynamic:{Boolean:r,Integer:s,Float:n,Array:$,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:F,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:r,Integer:s,Float:n,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:r,Float:n,Integer:s,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":L,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:C,lookupKernelValueType:function(e,t,r,n){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!r)throw new Error("precision missing");n.type&&(e=n.type);const s=C[r][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===s[e])return null;if(void 0===s[e])throw new Error(`Could not find a KernelValue for ${e}`);return s[e]}}}),et=e((e,t)=>{const{WebGLKernel:r}=xe(),{WebGL2FunctionNode:n}=ve(),{FunctionBuilder:s}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Se(),{lookupKernelValueType:h}=Qe();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends r{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,r,n){return h(e,t,r,n)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=s.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,r=e[0],n=e[1],s=new Float32Array(r*n);return t.readPixels(0,0,r,n,t.RED,t.FLOAT,s),s}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,r,n]=this.output;return this.transferValuesAsync().then(s=>e(s,t,r,n))}transferValuesAsync(){const{texSize:e,context:t}=this,r=e[0],n=e[1];let s,i,a;"single"===this.precision?(s=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(r*n*(this._tightRead?1:4))):(s=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(r*n*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,r,n,s,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((r,n)=>{let s,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),s=()=>i.port2.postMessage(0)):s=()=>setTimeout(o,0);const a=(r,n)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),r(n)},o=()=>{if(t.isContextLost())return a(n,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(r):i===t.WAIT_FAILED?a(n,new Error("clientWaitSync failed while awaiting kernel result")):void s()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),r=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const n=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,n,r[0],r[1]):e.texImage2D(e.TEXTURE_2D,0,n,r[0],r[1],0,n,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:r,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:r}=i(),{FunctionNode:n}=l();const s={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends n{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const r=this.getType(e.consequent),n=this.getType(e.alternate);if(null===r&&null===n)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let s="LiteralInteger"===r?"Number":r;"Integer"!==s||"Number"!==n&&"Float"!==n||(s="Number");const i=e=>{const r=this.getType(e);switch(s){case"Number":case"Float":"Integer"===r?this.castValueToFloat(e,t):"LiteralInteger"===r?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(e,t):"LiteralInteger"===r?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let r=0;r0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[n]=a="Number");const o=s[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${r.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let r=0;r>":!0,">>>":!0}[e.operator])return null;const r=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),r(e.left),t.push(") >> u32("),r(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(r(e.left),t.push(` ${e.operator} u32(`),r(e.right),t.push(")")):(r(e.left),t.push(` ${e.operator} `),r(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const n=this.getType(e),s=r.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n?(t.push(`user_${s}`),t):("Boolean"===n?t.push(`bool(params.user_${s})`):t.push(`params.user_${s}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const r=[],n=[],s=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,r);for(let e=0;e0&&t.push(r.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${n.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${s.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const r=this.getInternalVariableName("safeI");return t.push(`for (var ${r} : i32 = 0;${r}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const r in e)if("loc"!==r&&"range"!==r&&"parent"!==r&&t(e[r]))return!0;return!1};if(t(r[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",r[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(n[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(n[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:r}=e;if(1===r.length)return this.astGeneric(r[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:n,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const r={x:0,y:1,z:2}[i];if(void 0===r)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[r]}`):t.push(`${this.output[r]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(n){case"r":return t.push(`user_${r.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${r.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${r.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${r.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const r=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(r)):t.push(this.wgslInt(r)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(r)):t.push(this.wgslFloat(r)),t;case"Boolean":return t.push(r?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),n=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let r=0;r0&&t.push(", "),s){case"Integer":this.castValueToFloat(n,t);break;case"LiteralInteger":this.castLiteralToFloat(n,t);break;default:this.astGeneric(n,t)}}else{const s=this.lookupFunctionArgumentTypes(n)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(n,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${r.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const r=e.elements.length;t.push(`vec${r}(`);for(let n=0;n0&&t.push(", ");const r=e.elements[n];switch(this.getType(r)){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,r,n){return r?n.push(this.memberExpressionPropertyMarkup(r),", "):n.push("0, "),t?n.push(this.memberExpressionPropertyMarkup(t),", "):n.push("0, "),n.push(this.memberExpressionPropertyMarkup(e)),n}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let r=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(r)return r;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const s=await n.requestDevice({requiredLimits:{maxStorageBufferBindingSize:n.limits.maxStorageBufferBindingSize,maxBufferSize:n.limits.maxBufferSize}}),i={adapter:n,device:s,isLost:!1};return s.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),r===t&&(r=null)}),s.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{r===t&&(r=null)}),r=t}static destroy(){if(!r)return Promise.resolve();const e=r;return r=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),st=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WGSLFunctionNode:u}=tt(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends r{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;n.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&n.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${r[e].name} : array;`);n.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&n.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&n.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&n.push(f[e]);for(let t=0;t f32 {\n return user_${r}[u32(x + i32(params.user_${r}_dims.x) * (y + i32(params.user_${r}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&n.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):n.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),n.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,r=t.createShaderModule({code:this.compiledSource}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling WGSL compute shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:s,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(s[1]=Math.ceil(s[0]/i),s[0]=Math.ceil(s[0]/s[1])),a=s[0]*t);for(let e=0;e<3;e++)if(s[e]>i)throw new Error(`output dimension ${e} needs ${s[e]} workgroups, over this device's limit of ${i}`);return{groups:s,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const r=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),n=(await r.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(n.length>0)throw new Error("Error compiling the graphical blit shader:\n"+n.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,r]=this.threadDim,n=e*t*r*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=n||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(n,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:n,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const r=this._device.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(e>n)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${n} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let r=0;rthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,r=t.queue,{arrayArgs:n,scalarArgs:s,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let s=0;s{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return r.busy=!0,r}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const t=new Float32Array(i.buffer.getMappedRange(0,s).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,r,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,r]=this.output,n=t*r*4*4,s=this._acquireStaging(n),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,s.buffer,0,n),this._device.queue.submit([i.finish()]),s.buffer.mapAsync(1,0,n).then(()=>{const i=new Float32Array(s.buffer.getMappedRange(0,n).slice(0));s.buffer.unmap(),this._releaseStaging(s);const a=new Uint8ClampedArray(t*r*4);for(let n=0;n{throw this._releaseStaging(s),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const r={i32:127,i64:126,f32:125,f64:124,v128:123},n=new DataView(new ArrayBuffer(16));function s(e,t){let r=e>>>0;do{let e=127&r;r>>>=7,0!==r&&(e|=128),t.push(e)}while(0!==r)}function i(e,t){let r=0|e;for(;;){const e=127&r;if(r>>=7,0===r&&!(64&e)||-1===r&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,r){let n=e>>>0;for(let e=0;e<4;e++)t[r+e]=127&n|128,n>>>=7;t[r+4]=127&n}function o(e,t){const r=[];for(let t=0;t65535&&t++,n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<65536?r.push(224|n>>12,128|n>>6&63,128|63&n):r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n)}s(r.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(r in this.typeIndexByKey)return this.typeIndexByKey[r];const n=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[r]=n,n}addMemoryImport(e,t,r=!1){if(r&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:r},this}addFuncImport(e,t,r,n="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const s=this.funcImports.length;return this.funcImports.push({name:e,module:n,typeIndex:this._typeIndex(t,r)}),this.funcImportIndexByName[e]=s,s}addGlobal(e,t,r){return u(e),this.globals.push({type:e,mutable:t,initialValue:r}),this.globals.length-1}addFunction(e,{params:t=[],results:r=[],locals:n=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),r.forEach(u),n.forEach(u);const s=new h(this,e,t,r,n);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:s,typeIndex:this._typeIndex(t,r)}),s}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,r){r.push(e),s(t.length,r);for(let e=0;e0){const t=[];s(this.types.length,t);for(const{params:e,results:r}of this.types){t.push(96),s(e.length,t);for(const r of e)t.push(u(r));s(r.length,t);for(const e of r)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(s((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:r,shared:n}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=r;t.push(n?3:i?1:0),s(e,t),i&&s(r,t)}for(const{name:e,module:r,typeIndex:n}of this.funcImports)o(r,t),o(e,t),t.push(0),s(n,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{typeIndex:e}of this.functions)s(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];s(this.globals.length,t);for(const{type:e,mutable:r,initialValue:s}of this.globals){if(t.push(u(e),r?1:0),"i32"===e)t.push(65),i(s,t);else if("f32"===e){t.push(67),n.setFloat32(0,s,!0);for(let e=0;e<4;e++)t.push(n.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];s(this.exports.length,t);for(const{name:e,exportName:r}of this.exports)o(r,t),t.push(0),s(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];s(this.functions.length,t);for(const{emitter:e}of this.functions){const r=e.bytes.slice();for(const{at:t,name:n}of e.callFixups)a(this._resolveFuncIndex(n),r,t);const n=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}s(i.length,n);for(const{type:e,count:t}of i)s(t,n),n.push(e);for(let e=0;e{const{utils:r}=i(),{FunctionNode:n}=l(),{WasmFunctionEmitter:s}=it();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(s.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof s.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function T(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends n{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${r.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let r;if(this.isRootKernel)r=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>T("LiteralInteger"===e?"Number":e)),n=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":n.push("i32");break;case"Number":case"Float":case"LiteralInteger":n.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}r=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:n})}return this.walkFunction(r),!this.isRootKernel&&this.returnType&&r.unreachable(),r}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const r of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(r),n=this.argumentTypes[t];if("Number"!==n&&"Float"!==n&&"Integer"!==n&&"Boolean"!==n)continue;const s=this.assembler?this.assembler.layout.scalars[r]:null,i=s?s.offset:0,a="Integer"===n||"Boolean"===n?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(r,{kind:"scalar",index:o,wtype:a,gtype:n})}if(!this.isRootKernel){for(let e=0;e{if(n&&"object"==typeof n){if(Array.isArray(n))return n.forEach(r);if("FunctionDeclaration"!==n.type||n===e){"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==this.argumentNames.indexOf(n.left.name)&&t.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==this.argumentNames.indexOf(n.argument.name)&&t.add(n.argument.name);for(const e in n){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}}};return r(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const r=this.getType(e);return"f32"===t?"Integer"===r?this.castValueToFloat(e):"LiteralInteger"===r?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===r||"Float"===r?this.castValueToInteger(e):"LiteralInteger"===r?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(s));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(s):"Integer"===a?this.castValueToFloat(s):this.coerce(this.expression(s),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(s):"Number"===a||"Float"===a?this.castValueToInteger(s):this.coerce(this.expression(s),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(s));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(s)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,r,n){let s=this.locals.get(e);s&&"scalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.em.localSet(s.index)}declareVecLocal(e,t,r,n,s){const i=parseInt(t.substring(6),10);n.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const r=[];for(let e=0;ethis.em.localSet(r.index);else{if(r||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const r=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;n="Integer"===r||"Boolean"===r?"i32":"f32",this.em.i32Const(0),s=()=>"i32"===n?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.castValueToFloat(e.right),this.coerce("f32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.castLiteralToFloat(e.right),this.coerce("f32",n)):"Integer"===t&&"LiteralInteger"===r?(this.castLiteralToInteger(e.right),this.coerce("i32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.coerce(this.expression(e.right),n):(this.castValueToInteger(e.right),this.coerce("i32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),n)}s(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(!r||"scalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n="i32"===r.wtype,s=()=>n?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?n?"i32Add":"f32Add":n?"i32Sub":"f32Sub";return t?(this.em.localGet(r.index),s(),this.em[i]().localSet(r.index),"void"):(e.prefix?(this.em.localGet(r.index),s(),this.em[i]().localTee(r.index)):(this.em.localGet(r.index).localGet(r.index),s(),this.em[i]().localSet(r.index)),r.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const r=this.assembler?this.assembler.globals:{dataIndex:0},n=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),s=e.argument;if("ArrayExpression"===s.type){if(s.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:r}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(r),(e+10&&(r.push({tests:n,consequent:e[s].consequent}),n=[])):t=e[s].consequent;return{groups:r,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let r=0;r{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(r);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&r(e[t]))return!0;return!1};for(let e=0;e{const r=this.getType(t);switch(n){case"Number":case"Float":"Integer"===r?this.castValueToFloat(t):"LiteralInteger"===r?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===r||"Float"===r?this.castValueToInteger(t):"LiteralInteger"===r?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}};return this.emitCondition(e.test),this.enterIf(s),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===n?"bool":s}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),r)return this.emitMathCall(t,e);const n=this.getType(e),s=this.lookupFunctionArgumentTypes(t)||[];for(let r=0;r{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},n=u[e];if(n)return r(t.arguments[0]),this.em[n](),"f32";switch(e){case"round":return r(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return r(t.arguments[0]),"f32";case"min":case"max":{const n="min"===e?"f32Min":"f32Max";r(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const r=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(r),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),s=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(r.has(e.argument.name)||(r.add(e.argument.name),s=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(r.has(e.left.name)||(r.add(e.left.name),s=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const r=t||a(e.test);return u(e.consequent,r),u(e.alternate,r)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&u(n,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];n&&"object"==typeof n&&l(n,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const r=t||a(e.test);return!!h(e.consequent,r)||!!e.alternate&&h(e.alternate,r)}case"ConditionalExpression":{const r=t||a(e.test);return h(e.consequent,r)||h(e.alternate,r)}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,r)))}default:for(const r in e){if("loc"===r||"start"===r||"end"===r||"parent"===r)continue;const n=e[r];if(n&&"object"==typeof n&&h(n,t))return!0}return!1}},c=(e,n)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(r.has(u)||(r.add(u),s=!0),o(u)),(n||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,n);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(r.has(t)||(r.add(t),s=!0),o(t)),n&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,n));default:return u(e,n)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const r of e.declarations)r.init&&((t||a(r.init))&&o(r.id.name),u(r.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(n=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const r=t||a(e.test);return p(e.consequent,r),void(e.alternate&&p(e.alternate,r))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const r=t||!!e.test&&a(e.test)||h(e.body,!1);if(r){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,r),e.update&&c(e.update,r),void(e.test&&u(e.test,r))}case"SwitchStatement":{const r=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,r);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;s;)s=!1,p(e.body,!1);return{varying:t,varyingReturn:n,assignedArgs:r,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const r=this.vInnermostVaryingLoop();r&&(-1!==r.vBrk&&t.localGet(r.vBrk).v128Andnot(),-1!==r.vCnt&&t.localGet(r.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,r=!1;const n=e=>{if(!(!e||"object"!=typeof e||t&&r)){if(Array.isArray(e))return e.forEach(n);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(r=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&n(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];r&&"object"==typeof r&&n(r)}}};return n(e),{hasBreak:t,hasContinue:r}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const r=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),r.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),r.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),r.i32x4Splat(),this.vZero(),r.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return r.i32x4TruncSatF32x4S(),t;if("vbool"===t)return r.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return r.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),r.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return r.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return r.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const r=this.getType(e);return"vf32"===t?"Integer"===r?this.vCastValueToFloat(e):"LiteralInteger"===r?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(n));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(s,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(n):"Integer"===a?this.vCastValueToFloat(n):this.vCoerce(this.vexpr(n),"vf32")});break;case"Integer":this.vSetVaryingScalar(s,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(n):"Number"===a||"Float"===a?this.vCastValueToInteger(n):this.vCoerce(this.vexpr(n),"vi32")});break;case"Boolean":this.vSetVaryingScalar(s,"vi32","Boolean",()=>{this.vexprMask(n),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,r,n){let s=this.locals.get(e);s&&"vscalar"===s.kind&&s.wtype===t?s.gtype=r:(s={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:r},this.locals.set(e,s)),n(),this.vSetLocal(s.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,r=this.locals.get(t);if(r&&"scalar"===r.kind)return this.emitAssignment(e);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const n=r.wtype;if("="===e.operator){const t=this.getType(e.left),r=this.getType(e.right);"Integer"!==t&&"Integer"===r?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",n)):"Integer"!==t&&"LiteralInteger"===r?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",n)):"Integer"===t&&"LiteralInteger"===r?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",n)):"Integer"!==t||"Number"!==r&&"Float"!==r?this.vCoerce(this.vexpr(e.right),n):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",n))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),n)}this.vSetLocal(r.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const r=this.locals.get(e.argument.name);if(r&&"scalar"===r.kind)return this.emitUpdate(e,t);if(!r||"vscalar"!==r.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const n=this.em,s="vi32"===r.wtype,i=()=>s?n.v128ConstI32x4(1,1,1,1):n.v128ConstF32x4(1,1,1,1),a="++"===e.operator?s?"i32x4Add":"f32x4Add":s?"i32x4Sub":"f32x4Sub";if(t)return n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),"void";if(e.prefix)n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(r.index);else{const e=n.addLocal("v128");n.localGet(r.index).localSet(e),n.localGet(r.index),i(),n[a](),this.vSetLocal(r.index),n.localGet(e)}return r.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(n)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const r=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const r=parseInt(this.returnType.substring(6),10),n=e.argument,s=[];if("ArrayExpression"===n.type){if(n.elements.length!==r)throw this.astErrorOutput(`expected ${r} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===s)return t.globalGet(r.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(n,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(n,2),t.localGet(i).v128Bitselect(),t.v128Store(n,2)));t.globalGet(r.dataIndex).i32Const(s).i32Mul().i32Const(2).i32Shl().localSet(a);for(let r=0;r<4;r++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!s){let s,a;switch(i){case"Float":case"Number":a=!1,s=n.addLocal("f32"),this.coerce(this.expression(t),"f32"),n.localSet(s);break;case"Integer":a=!0,s=n.addLocal("i32"),this.coerce(this.expression(t),"i32"),n.localSet(s);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===r.length&&!r[0].test)return void this.vEmitSwitchConsequent(r[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(r),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:r}=o[e];for(let e=0;e0&&n.i32Or();this.enterIf(),this.vEmitSwitchConsequent(r),(e+10&&n.v128Or();n.localSet(p),this.vRecomputeCur(h),n.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),n.localGet(c).localGet(p).v128Or().localSet(c),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(r),this.exit()}l&&(this.vRecomputeCur(h),n.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),n.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const r=this.getType(e);t?"Number"===r||"Float"===r?this.vCastValueToInteger(e):"LiteralInteger"===r?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===r?this.vCastLiteralToFloat(e):"Integer"===r?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),r=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const r=this.getType(t);switch(s){case"Number":case"Float":"Integer"===r?this.vCastValueToFloat(t):"LiteralInteger"===r?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===r||"Float"===r?this.vCastValueToInteger(t):"LiteralInteger"===r?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${s}`,e)}},a="Integer"===s?"vi32":"Boolean"===s?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const r=t.addLocal("v128");this.vexprMask(e.test),t.localSet(r);const n=t.addLocal("v128");t.localGet(this.vCur).localSet(n),t.localGet(n).localGet(r).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(n).localGet(r).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(n).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const r=this.isAstMathFunction(e);if(t=r||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return r?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const r=this.em,n=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},s=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let n=0;n0&&r.i32Const(t).i32Add(),r.globalSet(s.threadX)),n.usesRandom&&r.localGet(c).i32x4ExtractLane(t).globalSet(s.pcgState);for(const e of o)r.localGet(e.index),"vi32"===e.wtype?r.i32x4ExtractLane(t):r.f32x4ExtractLane(t);r.call(this.mangleFunctionName(e)),"void"!==u&&r.localSet(l),n.usesRandom&&r.localGet(c).globalGet(s.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(r.localGet(l),"i32"===u?r.i32x4Splat():r.f32x4Splat(),r.localSet(h)):(r.localGet(h).localGet(l),"i32"===u?r.i32x4ReplaceLane(t):r.f32x4ReplaceLane(t),r.localSet(h)))}return n.readsThread&&r.localGet(this._vBaseX).globalSet(s.threadX),n.usesRandom&&(r.localGet(c).globalGet(s.pcgStateV),this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.v128Bitselect().globalSet(s.pcgStateV)),"void"===u?"void":(r.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const r=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?r.localGet(this.vCur):r.v128ConstI32x4(-1,-1,-1,-1),r.call("pcg_random_v"),"vf32";const n=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},s=v[e];if(s)return n(t.arguments[0]),r[s](),"vf32";switch(e){case"round":return n(t.arguments[0]),r.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return n(t.arguments[0]),"vf32";case"min":case"max":{const s="min"===e?"f32x4Min":"f32x4Max";n(t.arguments[0]);for(let e=1;e{r.localGet(e.indices[t]),"vec"===e.kind&&r.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return n(t.value),"vf32"}const s=r.addLocal("v128");this.vEmitIndex(t),r.localSet(s);const i=r.addLocal("v128");n(0),r.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const r=e[t];if(r&&"object"==typeof r&&this.isThreadDependent(r))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ot=e((e,t)=>{let n=null;try{n=r()}catch(e){}const s="function"==typeof Worker;const i="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(n&&"function"==typeof n.cpus){const e=n.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const r of t.settingUp.values())r.reject(e);t.settingUp.clear();for(const r of t.pending.values())r.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const n=r=>{if("ready"===r.type){const n=t.settingUp.get(r.id);n&&(t.settingUp.delete(r.id),t.setup.add(r.id),this._updateRef(e),n.resolve())}else if("done"===r.type){const n=t.pending.get(r.taskId);n&&(t.pending.delete(r.taskId),this._updateRef(e),n.resolve())}};let a;if(s){const t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));a=new Worker(t),URL.revokeObjectURL(t),a.onmessage=e=>n(e.data),a.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=r();a=new t(i,{eval:!0}),a.on("message",n),a.on("error",t=>e.die(t)),a.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),a.unref()}return e.handle=a,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let r=e.state.settingUp.get(t.id);return r||(r={},r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),e.state.settingUp.set(t.id,r),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),r.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const r=t.map((t,r)=>{const n=this._worker(r);return this._ensureSetup(n,e).then(()=>new Promise((r,s)=>{if(n.dead)return void s(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;n.state.pending.set(i,{resolve:r,reject:s}),this._updateRef(n),n.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(r).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const r=[];for(let n=0;nnew Promise((r,i)=>{if(s.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;s.state.pending.set(a,{resolve:r,reject:i}),this._updateRef(s),s.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[n],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(r).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const r=t.state.settingUp.get(e);r&&(t.state.settingUp.delete(e),r.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),ut=e((e,t)=>{const{Kernel:r}=a(),{FunctionBuilder:s}=o(),{WebAssemblyFunctionNode:u}=at(),{WasmModuleBuilder:l}=it(),{WebAssemblyWorkerPool:h}=ot(),{utils:c}=i(),{Input:p}=n(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends r{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,r,n,s){if(!t||0===r)return e(0,r,s),"scalar";if(!(3&n))return t(0,r,s),"simd";const i=-4&n,a=r/n;for(let r=0;r0&&t(a,a+i,s),e(a+i,a+n,s)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let r=0;const n={},s={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,r,n){const s=new l,i=t.totalBytes||t.outputOffset+r*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);s.addMemoryImport(a,o,n);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];s.addFuncImport("math_"+e,t,["f32"])}const h={threadX:s.addGlobal("i32",!0,0),threadY:s.addGlobal("i32",!0,0),threadZ:s.addGlobal("i32",!0,0),dataIndex:s.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=s.addGlobal("i32",!0,0),this._emitPcgRandom(s,h.pcgState));const c={module:s,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(r.output=this.output,r.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=s.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),s.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=s.addGlobal("v128",!0,0),this._emitPcgRandomVector(s,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const r=this.functionBuilder.functionMap[t];r&&(e||(e={readsThread:!1,usesRandom:!1}),r.readsThread&&(e.readsThread=!0),r.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(s,h),s.exportFunction("run_simd")}return{bytes:s.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[r,n]=this.threadDim,s=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});s.localGet(0).localSet(3),1===this.output.length?(s.i32Const(0).globalSet(t.threadY),s.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&s.i32Const(0).globalSet(t.threadZ),s.block(),s.localGet(3).localGet(1).i32GeS().brIf(0),s.loop(),s.localGet(3).globalSet(t.dataIndex),1===this.output.length?s.localGet(3).globalSet(t.threadX):2===this.output.length?(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().globalSet(t.threadY)):(s.localGet(3).i32Const(r).i32RemU().globalSet(t.threadX),s.localGet(3).i32Const(r).i32DivU().i32Const(n).i32RemU().globalSet(t.threadY),s.localGet(3).i32Const(r*n).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(s.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),s.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),s.localGet(2).i32x4Splat().i32x4Add(),s.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),s.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),s.globalSet(t.pcgStateV)),s.call("kernel_simd"),s.localGet(3).i32Const(4).i32Add().localSet(3),s.localGet(3).localGet(1).i32LtS().brIf(0),s.end(),s.end()}_emitPcgRandomVector(e,t){const r=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),n=r.addLocal("v128"),s=r.addLocal("i32");r.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),r.globalGet(t).localSet(n),r.localGet(n).i32x4ExtractLane(0).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)r.localGet(n).i32x4ExtractLane(e).localSet(s),r.localGet(s).localGet(s).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);r.localGet(n).v128Xor(),r.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=r.addLocal("v128");r.localTee(i),r.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),r.i32Const(8).i32x4ShrU(),r.f32x4ConvertI32x4U(),r.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const r=e.addFunction("pcg_random",{params:[],results:["f32"]}),n=r.addLocal("i32");r.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),r.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(n),r.i32Const(22).i32ShrU().localGet(n).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const r=this._pool;this._threadedTail.then(()=>{r.release(e.id),t()},t)}else t()}_instantiate(e,t){let r=this._moduleCache.get(e);if(r&&(this._moduleCache.delete(e),this._moduleCache.set(e,r)),!r){const n=this._threadable(),s=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(s,u,n);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=n?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);r={id:g++,sizeSignature:e,shared:n,layout:s,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in s.constantArrays){const t=s.constantArrays[e],n=this.constants[e];c.flattenTo(n instanceof p?n.value:n,r.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,r);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=r}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,s,t[0],l);const h=n.outputOffset/4,d=i.slice(h,h+s*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:r,cells:n}=t,s=0===this._threadedBusy;let i=null,a=null;if(s){for(const n in r.arrays){const s=r.arrays[n],i=e[s.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(s.offset/4,s.offset/4+s.flatLength))}for(const n in r.scalars){const s=r.scalars[n],i=e[s.index];"Integer"===s.type?t.i32[s.offset/4]=0|i:"Boolean"===s.type?t.i32[s.offset/4]=i?1:0:t.f32[s.offset/4]=i}}else{i=[];for(const t in r.arrays){const n=r.arrays[t],s=e[n.index],a=new Float32Array(n.flatLength);c.flattenTo(s instanceof p?s.value:s,a),i.push({record:n,flat:a})}a=[];for(const t in r.scalars){const n=r.scalars[t];a.push({record:n,value:e[n.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=n)break;h.push({start:r,end:t===e-1?n:Math.min(r+s,n),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=r.outputOffset/4,s=t.f32.slice(e,e+n*l);return this._shapeOutput(s,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,r){const[n,s,i]=[t[0],t[1]||1,t[2]||1];if(1===r)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,n);case 2:return c.erectMemoryOptimized2DFloat(e,n,s);default:return c.erectMemoryOptimized3DFloat(e,n,s,i)}const a=r,o=t=>{const r=new Array(n);for(let s=0;s{const{utils:r}=i(),{Input:s}=n(),{WebAssemblyKernel:a}=ut(),{WebAssemblyWorkerPool:o}=ot(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let d=n.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:n.size,kernel:e,constantRegions:null},n.set(p,d)}u[s]=d,c[s]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let r=0;re&&(e=s)}const r=new o;f=Math.min(r.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=r,m=d(12)):r.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],T=[],S=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:s.arrays,scalars:s.scalars,constantArrays:r.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=n._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of n.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),L.push(Array.from(n.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:n.threadDim[0],usesRandom:n.usesRandom,randomSeed:n.randomSeed}}if(this.threaded){const e=[];for(let r=0;r=t?(n[2*e]=0,n[2*e+1]=0):(n[2*e]=i,n[2*e+1]=r===f-1?t:Math.min(i+s,t))}e.push(n)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:L,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const r=e.binding;if("step"===r.source){const e=r.step,n=w[t.steps[e].outputBuffer],s=u[e].kernel;return{kind:"step",base:n.offset/4,count:n.cells*s.componentCount,output:t.steps[e].output,componentCount:s.componentCount,kernel:s}}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,r=this.i32,n=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(r,t.countIndex,0),Atomics.store(r,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const s=Atomics.load(r,t.genIndex),i=s+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:s,seeds:n}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,r=this._entry.genIndex,n="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((s,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,r),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,r);if(a>=e)return void o(s);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(n){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),s=n(t,r,a,e);s.async?s.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{utils:r}=i(),{Input:s}=n(),{FusionFallback:a}=lt();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,r){const n=e.limits,s=Math.min(n.maxStorageBufferBindingSize,n.maxBufferSize);if(t>s)throw new a(`${r} needs ${t} bytes but this device allows ${s} per storage buffer`)}function l(e){const t=e instanceof s?Array.from(e.size):Array.from(r.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof s)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,r,n){for(let e=0;er.getVariableType(e,h)).join(",");let p=n.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:n.size,kernel:e},n.set(c,p)}o[s]=p}this._scratch=null;for(let e=0;e{const r=e.output;let n=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let n=0;n{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),T=null!==f.randomSeedOffset&&null===d.randomSeed,S=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(T?"#"+n:"");let A=g.get(S);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),r=new Int32Array(e),n=new Float32Array(e),s=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=s.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||T;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const r=e.binding;if("step"===r.source){const e=t.steps[r.step],n=this._planBuffers[e.outputBuffer],s=o[r.step].kernel,i=n.cells*s.componentCount*4,a={kind:"step",buffer:n.buffer,offset:y,byteLength:i,output:e.output,componentCount:s.componentCount,kernel:s};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===r.source?{kind:"arg",index:r.index}:{kind:"literal",value:r.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const r=new Array(e.argBindings.length);for(let n=0;n>>0),n.writeBuffer(r.paramsBuffer,0,r.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),r=this._shapeResults(e,t);return this._staging.unmap(),r}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const r=this.plan.results,n=new Array(this._resultReads.length);for(let r=0;r{const{Input:r}=n(),{utils:s}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),r=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(r,e),r}recordKernelCall(e,t){const r=e.kernel;if(r.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(r.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(r.subKernels&&r.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!r.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let n=this.kernelIndexes.get(e);void 0===n&&(n=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,n));const s=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,n)}),i=()=>{this._inFlight--,r.length>0&&m(r)};return s.then(i,i),this._tail=s.then(b,b),s}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let r=0;r({key:r,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&null!==r)throw new Error(o);const n=[];for(const r in t)t.hasOwnProperty(r)&&n.push({key:r,binding:e.bindValue(t[r])});if(0===n.length)throw new Error(o);return{kind:"object",entries:n}}throw new Error(o)}(e,n),i=function(e,t){const r=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:s,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const r=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),n=t.kernel+":"+t.outputBuffer+":"+r;let s=e.genericClones.get(n);return s||(s=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(n,s)),s}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ht();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=lt();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const r=e.kernel,n=Object.assign({output:Array.from(r.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),s=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];r.declaredArgumentTypes&&(n.argumentTypes=r.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];s=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(n,s)}return s(r)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const n=new Array(t.length).fill(null);for(let s=0;s0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=n||new Array(t.length).fill(null);if(a&&!n)for(let n=0;n{const{utils:r}=i(),{Input:s}=n(),{getActiveTrace:a}=ct();function o(e,t){if(t.kernel)return void(t.kernel=e);const n=r.allPropertiesOf(e);for(let r=0;rt.kernel[s]),t.__defineSetter__(s,e=>{t.kernel[s]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let n=e.switchingKernels?void 0:e.run.apply(e,t);for(let s=0;e.switchingKernels;s++){if(s>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${r(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),n=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(n=e.run.apply(e,t))}return n}function r(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function n(r){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const s=l(r);return t(s,e).then(e=>(e&&p.replaceKernel(e),n(s)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,r),Promise.resolve(e.run.apply(e,r));for(let e=0;en(e));const s=t(r);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(s)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),r=[];for(let e=0;e{t[n]=e}))}return Promise.all(r).then(()=>t)}function l(e){const t=new Array(e.length);for(let r=0;r{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),dt=e((e,r)=>{const{gpuMock:n}=t(),{utils:s}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=be(),{WebGL2Kernel:h}=et(),{WebGLKernel:c}=xe(),{WebGPUKernel:d}=st(),{WebAssemblyKernel:f}=ut(),{kernelRunShortcut:m}=pt(),{Pipeline:g}=ct(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function T(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(s.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(s.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(s.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(s.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}r.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;er.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const r=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});r.fallbackReason=y.fallbackReason,r.build.apply(r,e);const n=r.run.apply(r,e);return y.replaceKernel(r),!l.canvas&&r.canvas&&(l.canvas=r.canvas),!l.context&&r.context&&(l.context=r.context),n}function c(e,r,n){n.debug&&console.warn("Switching kernels");let s=null;if(n.signature&&!a[n.signature]&&(a[n.signature]=n),n.dynamicOutput)for(let t=e.length-1;t>=0;t--){const r=e[t];"outputPrecisionMismatch"===r.type&&(s=r.needed)}const o=n.constructor,u=o.getArgumentTypes(n,r),l=o.getSignature(n,u),p=a[l];if(p)return p.onActivate(n),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:n.constantTypes,graphical:n.graphical,loopMaxIterations:n.loopMaxIterations,constants:n.constants,dynamicOutput:n.dynamicOutput,dynamicArgument:n.dynamicArguments,context:n.context,canvas:n.canvas,output:s||n.output,precision:n.precision,pipeline:n.pipeline,immutable:n.immutable,optimizeFloatMemory:n.optimizeFloatMemory,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,subKernels:n.subKernels,strictIntegers:n.strictIntegers,randomSeed:n.randomSeed,debug:n.debug,asyncMode:n.asyncMode,gpu:n.gpu,validate:v,returnType:n.returnType,tactic:n.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:n.texture,mappedTextures:n.mappedTextures,drawBuffersMap:n.drawBuffersMap});return d.build.apply(d,r),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const r=this;f.onAsyncModeUpgrade=function(n,s){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(s.graphical)return s.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:s.functions,nativeFunctions:s.nativeFunctions,injectedNative:s.injectedNative,gpu:r,validate:v,asyncMode:!0,output:s.output,pipeline:s.pipeline,immutable:s.immutable,dynamicOutput:s.dynamicOutput,dynamicArguments:!0,loopMaxIterations:s.loopMaxIterations,constants:s.constants,constantTypes:s.constantTypes,argumentTypes:s.argumentTypes,precision:s.precision,tactic:s.tactic,strictIntegers:s.strictIntegers,fixIntegerDivisionAccuracy:s.fixIntegerDivisionAccuracy,subKernels:s.subKernels,graphical:s.graphical,debug:s.debug}),a.build.apply(a,n)}catch(e){return s.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(s.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const r=new g(this,e,t);this.pipelines.push(r);const n=function(){return r.call(arguments)};return n.pipeline=r,n.setConstants=function(e){return r.setConstants(e),n},n.destroy=function(){return r.destroy()},Object.defineProperty(n,"executorKind",{get:()=>r.executorKind}),Object.defineProperty(n,"fallbackReason",{get:()=>r.fallbackReason}),Object.defineProperty(n,"plan",{get:()=>r.plan}),Object.defineProperty(n,"backend",{get:()=>{const e=r.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=r.plan;if(!t)return null;for(const[e,r]of t.genericClones)if(0!==e.indexOf("up:"))return r.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),n}createKernelMap(){let e,t;const r=typeof arguments[arguments.length-2];if("function"===r||"string"===r?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const n=T(t);if(t&&"object"==typeof t.argumentTypes&&(n.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){n.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},r)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let r=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();r=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const n=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:r}=i();t.exports={alias:function(e,t){const n=t.toString();return new Function(`return function ${e} (${r.getArgumentNamesFromString(n).join(", ")}) {\n ${r.getFunctionBodyFromString(n)}\n}`)()}}}),mt=e((e,t)=>{const{GPU:r}=dt(),{alias:c}=ft(),{utils:d}=i(),{Input:f,input:m}=n(),{Texture:g}=s(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:T}=be(),{WebGLFunctionNode:S}=G(),{WebGLKernel:A}=xe(),{kernelValueMaps:w}=ye(),{WebGL2FunctionNode:_}=ve(),{WebGL2Kernel:E}=et(),{kernelValueMaps:I}=Qe(),{WGSLFunctionNode:k}=tt(),{WebGPUKernel:L}=st(),{WebGPUContext:F}=rt(),{WebGPUBufferResult:$}=nt(),{WebAssemblyFunctionNode:C}=at(),{WebAssemblyKernel:M}=ut(),{GLKernel:O}=D(),{Kernel:N}=a(),{FunctionTracer:z}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:r,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:T,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:S,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:L,WebGPUContext:F,WebGPUBufferResult:$,WebAssemblyFunctionNode:C,WebAssemblyKernel:M,GLKernel:O,Kernel:N,FunctionTracer:z,plugins:{mathRandom:R()}}});return e((e,t)=>{const r=mt(),n=r.GPU;for(const e in r)r.hasOwnProperty(e)&&"GPU"!==e&&(n[e]=r[e]);function s(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>n,set(){}})}n.GPU=n,"undefined"!=typeof window&&s(window),"undefined"!=typeof self&&s(self),t.exports=n})()}); \ No newline at end of file diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index 18c0e75c..c58a9649 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License @@ -24582,7 +24582,7 @@ const sampled = new Array(args.length); const held = []; let preUploaded = null; - if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); + if (this._inFlight === 0 && this.plan && this._executor === false && this._genericEagerUploadsPay(this.plan)) preUploaded = this._eagerUploads(this.plan, args); for (let i = 0; i < args.length; i++) if (preUploaded && preUploaded[i]) sampled[i] = args[i]; else sampled[i] = snapshotValue(args[i], held); this._inFlight++; const promise = this._tail.then(async () => { @@ -24778,6 +24778,10 @@ const value = args[binding.index]; if (!value || typeof value !== "object") continue; if (typeof value.toArray === "function" && !(value instanceof Input)) continue; + if (plan.genericArgDims) { + const known = plan.genericArgDims.get(binding.index); + if (known !== void 0 && known !== argDimensions(value).join("x")) return null; + } const handle = this._uploadArg(plan, binding.index, value); if (handle && typeof handle.then === "function") return null; uploaded[binding.index] = handle; diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index c5655d54..d5d6342a 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,11 +5,11 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:13:48 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License * * Copyright (c) 2026 gpu.js Team */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,r)}),i=()=>{this._inFlight--,s.length>0&&m(s)};return n.then(i,i),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const r=new Array(t.length).fill(null);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=r||new Array(t.length).fill(null);if(a&&!r)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>{const e=s.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=s.plan;if(!t)return null;for(const[e,s]of t.genericClones)if(0!==e.indexOf("up:"))return s.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).GPU=t()}(this,function(){var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e,t)=>{function s(e){const t=new Array(e.length);for(let s=0;s{e.output=l(t),e.graphical&&u(e)},e.toJSON=()=>{throw new Error("Not usable with gpuMock")},e.setConstants=t=>(e.constants=t,e),e.setGraphical=t=>(e.graphical=t,e),e.setCanvas=t=>(e.canvas=t,e),e.setContext=t=>(e.context=t,e),e.destroy=()=>{},e.validateSettings=()=>{},e.graphical&&e.output&&u(e),e.exec=function(){return new Promise((t,s)=>{try{t(e.apply(e,arguments))}catch(e){s(e)}})},e.getPixels=t=>{const{x:s,y:r}=e.output;return t?function(e,t,s){const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee,s=["setWarnVarUsage","setArgumentTypes","setTactic","setOptimizeFloatMemory","setDebug","setLoopMaxIterations","setConstantTypes","setFunctions","setNativeFunctions","setInjectedNative","setPipeline","setPrecision","setOutputToTexture","setImmutable","setStrictIntegers","setDynamicOutput","setHardcodeConstants","setDynamicArguments","setUseLegacyEncoder","setWarnVarUsage","addSubKernel"];for(let r=0;r{var s,r;s=e,r=function(e){"use strict";var t=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],s=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],r="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",n={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",a={5:i,"5module":i+" export import",6:i+" const class extends export import super"},o=/^in(stanceof)?$/,u=new RegExp("["+r+"]"),l=new RegExp("["+r+"\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65]");function h(e,t){for(var s=65536,r=0;re)return!1;if((s+=t[r+1])>=e)return!0}return!1}function c(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&u.test(String.fromCharCode(e)):!1!==t&&h(e,s)))}function p(e,r){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&l.test(String.fromCharCode(e)):!1!==r&&(h(e,s)||h(e,t)))))}var d=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function f(e,t){return new d(e,{beforeExpr:!0,binop:t})}var m={beforeExpr:!0},g={startsExpr:!0},y={};function x(e,t){return void 0===t&&(t={}),t.keyword=e,y[e]=new d(e,t)}var b={num:new d("num",g),regexp:new d("regexp",g),string:new d("string",g),name:new d("name",g),privateId:new d("privateId",g),eof:new d("eof"),bracketL:new d("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new d("]"),braceL:new d("{",{beforeExpr:!0,startsExpr:!0}),braceR:new d("}"),parenL:new d("(",{beforeExpr:!0,startsExpr:!0}),parenR:new d(")"),comma:new d(",",m),semi:new d(";",m),colon:new d(":",m),dot:new d("."),question:new d("?",m),questionDot:new d("?."),arrow:new d("=>",m),template:new d("template"),invalidTemplate:new d("invalidTemplate"),ellipsis:new d("...",m),backQuote:new d("`",g),dollarBraceL:new d("${",{beforeExpr:!0,startsExpr:!0}),eq:new d("=",{beforeExpr:!0,isAssign:!0}),assign:new d("_=",{beforeExpr:!0,isAssign:!0}),incDec:new d("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new d("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:f("||",1),logicalAND:f("&&",2),bitwiseOR:f("|",3),bitwiseXOR:f("^",4),bitwiseAND:f("&",5),equality:f("==/!=/===/!==",6),relational:f("/<=/>=",7),bitShift:f("<>/>>>",8),plusMin:new d("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:f("%",10),star:f("*",10),slash:f("/",10),starstar:new d("**",{beforeExpr:!0}),coalesce:f("??",1),_break:x("break"),_case:x("case",m),_catch:x("catch"),_continue:x("continue"),_debugger:x("debugger"),_default:x("default",m),_do:x("do",{isLoop:!0,beforeExpr:!0}),_else:x("else",m),_finally:x("finally"),_for:x("for",{isLoop:!0}),_function:x("function",g),_if:x("if"),_return:x("return",m),_switch:x("switch"),_throw:x("throw",m),_try:x("try"),_var:x("var"),_const:x("const"),_while:x("while",{isLoop:!0}),_with:x("with"),_new:x("new",{beforeExpr:!0,startsExpr:!0}),_this:x("this",g),_super:x("super",g),_class:x("class",g),_extends:x("extends",m),_export:x("export"),_import:x("import",g),_null:x("null",g),_true:x("true",g),_false:x("false",g),_in:x("in",{beforeExpr:!0,binop:7}),_instanceof:x("instanceof",{beforeExpr:!0,binop:7}),_typeof:x("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:x("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:x("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},v=/\r\n?|\n|\u2028|\u2029/,S=new RegExp(v.source,"g");function T(e){return 10===e||13===e||8232===e||8233===e}function A(e,t,s){void 0===s&&(s=e.length);for(var r=t;r>10),56320+(1023&e)))}var R=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,N=function(e,t){this.line=e,this.column=t};N.prototype.offset=function(e){return new N(this.line,this.column+e)};var M=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function G(e,t){for(var s=1,r=0;;){var n=A(e,r,t);if(n<0)return new N(s,t-r);++s,r=n}}var O={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},V=!1;function P(e){var t={};for(var s in O)t[s]=e&&C(e,s)?e[s]:O[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!V&&"object"==typeof console&&console.warn&&(V=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),L(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return L(t.onComment)&&(t.onComment=function(e,t){return function(s,r,n,i,a,o){var u={type:s?"Block":"Line",value:r,start:n,end:i};e.locations&&(u.loc=new M(this,a,o)),e.ranges&&(u.range=[n,i]),t.push(u)}}(t,t.onComment)),t}var B=256;function z(e,t){return 2|(e?4:0)|(t?8:0)}var U=function(e,t,s){this.options=e=P(e),this.sourceFile=e.sourceFile,this.keywords=F(a[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var r="";!0!==e.allowReserved&&(r=n[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(r+=" await")),this.reservedWords=F(r);var i=(r?r+" ":"")+n.strict;this.reservedWordsStrict=F(i),this.reservedWordsStrictBind=F(i+" "+n.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(v).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=b.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},K={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};U.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},K.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},K.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},K.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&B)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},K.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(64&t)>0||s||this.options.allowSuperOutsideMethod},K.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},K.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},K.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,s=e.inClassFieldInit;return(258&t)>0||s},K.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&B)>0},U.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,r=0;r=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(r+1))}e+=t[0].length,_.lastIndex=e,e+=_.exec(this.input)[0].length,";"===this.input[e]&&e++}},W.eat=function(e){return this.type===e&&(this.next(),!0)},W.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc},W.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},W.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},W.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))},W.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},W.semicolon=function(){this.eat(b.semi)||this.insertSemicolon()||this.unexpected()},W.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},W.expect=function(e){this.eat(e)||this.unexpected()},W.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var q=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};W.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},W.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,r=e.doubleProto;if(!t)return s>=0||r>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")},W.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&r<56320)return!0;if(c(r,!0)){for(var n=s+1;p(r=this.input.charCodeAt(n),!0);)++n;if(92===r||r>55295&&r<56320)return!0;var i=this.input.slice(s,n);if(!o.test(i))return!0}return!1},X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;_.lastIndex=this.pos;var e,t=_.exec(this.input),s=this.pos+t[0].length;return!(v.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(p(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},X.parseStatement=function(e,t,s){var r,n=this.type,i=this.startNode();switch(this.isLet(e)&&(n=b._var,r="let"),n){case b._break:case b._continue:return this.parseBreakContinueStatement(i,n.keyword);case b._debugger:return this.parseDebuggerStatement(i);case b._do:return this.parseDoStatement(i);case b._for:return this.parseForStatement(i);case b._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case b._class:return e&&this.unexpected(),this.parseClass(i,!0);case b._if:return this.parseIfStatement(i);case b._return:return this.parseReturnStatement(i);case b._switch:return this.parseSwitchStatement(i);case b._throw:return this.parseThrowStatement(i);case b._try:return this.parseTryStatement(i);case b._const:case b._var:return r=r||this.value,e&&"var"!==r&&this.unexpected(),this.parseVarStatement(i,r);case b._while:return this.parseWhileStatement(i);case b._with:return this.parseWithStatement(i);case b.braceL:return this.parseBlock(!0,i);case b.semi:return this.parseEmptyStatement(i);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){_.lastIndex=this.pos;var a=_.exec(this.input),o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(40===u||46===u)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===b._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.value,h=this.parseExpression();return n===b.name&&"Identifier"===h.type&&this.eat(b.colon)?this.parseLabeledStatement(i,l,h,e):this.parseExpressionStatement(i,h)}},X.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(b.semi)||this.insertSemicolon()?e.label=null:this.type!==b.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(b.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},X.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(H),this.enterScope(0),this.expect(b.parenL),this.type===b.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===b._var||this.type===b._const||s){var r=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(r,!0,n),this.finishNode(r,"VariableDeclaration"),(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===r.declarations.length?(this.options.ecmaVersion>=9&&(this.type===b._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,r)):(t>-1&&this.unexpected(t),this.parseFor(e,r))}var i=this.isContextual("let"),a=!1,o=this.containsEsc,u=new q,l=this.start,h=t>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===b._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===b._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(h.start!==l||o||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),i&&a&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,u),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},X.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,J|(s?0:Q),!1,t)},X.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(b._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},X.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(b.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},X.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(b.braceL),this.labels.push(Y),this.enterScope(0);for(var s=!1;this.type!==b.braceR;)if(this.type===b._case||this.type===b._default){var r=this.type===b._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(b.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},X.parseThrowStatement=function(e){return this.next(),v.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Z=[];X.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(b.parenR),e},X.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===b._catch){var t=this.startNode();this.next(),this.eat(b.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(b._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},X.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},X.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(H),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},X.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},X.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},X.parseLabeledStatement=function(e,t,s,r){for(var n=0,i=this.labels;n=0;o--){var u=this.labels[o];if(u.statementStart!==e.start)break;u.statementStart=this.start,u.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(r?-1===r.indexOf("label")?r+"label":r:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(b.braceL),e&&this.enterScope(0);this.type!==b.braceR;){var r=this.parseStatement(null);t.body.push(r)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},X.parseFor=function(e,t){return e.init=t,this.expect(b.semi),e.test=this.type===b.semi?null:this.parseExpression(),this.expect(b.semi),e.update=this.type===b.parenR?null:this.parseExpression(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t){var s=this.type===b._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(b.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},X.parseVar=function(e,t,s,r){for(e.declarations=[],e.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(b.eq)?n.init=this.parseMaybeAssign(t):r||"const"!==s||this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")?r||"Identifier"===n.id.type||t&&(this.type===b._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(b.comma))break}return e},X.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var J=1,Q=2;function ee(e,t){var s=t.key.name,r=e[s],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===r&&"iset"===n||"iset"===r&&"iget"===n||"sget"===r&&"sset"===n||"sset"===r&&"sget"===n?(e[s]="true",!1):!!r||(e[s]=n,!1)}function te(e,t){var s=e.computed,r=e.key;return!s&&("Identifier"===r.type&&r.name===t||"Literal"===r.type&&r.value===t)}X.parseFunction=function(e,t,s,r,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===b.star&&t&Q&&this.unexpected(),e.generator=this.eat(b.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&J&&(e.id=4&t&&this.type!==b.name?null:this.parseIdent(),!e.id||t&Q||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(z(e.async,e.generator)),t&J||(e.id=this.type===b.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,n),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&J?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(b.parenL),e.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},X.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),n=this.startNode(),i=!1;for(n.body=[],this.expect(b.braceL);this.type!==b.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(i&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),i=!0):a.key&&"PrivateIdentifier"===a.key.type&&ee(r,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},X.parseClassElement=function(e){if(this.eat(b.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),r="",n=!1,i=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(b.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===b.star?o=!0:r="static"}if(s.static=o,!r&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==b.star||this.canInsertSemicolon()?r="async":i=!0),!r&&(t>=9||!i)&&this.eat(b.star)&&(n=!0),!r&&!i&&!n){var u=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=u:r=u)}if(r?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=r,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===b.parenL||"method"!==a||n||i){var l=!s.static&&te(s,"constructor"),h=l&&e;l&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,i,h)}else this.parseClassField(s);return s},X.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword},X.parseClassElementName=function(e){this.type===b.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},X.parseClassMethod=function(e,t,s,r){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):e.static&&te(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var i=e.value=this.parseMethod(t,s,r);return"get"===e.kind&&0!==i.params.length&&this.raiseRecoverable(i.start,"getter should have no params"),"set"===e.kind&&1!==i.params.length&&this.raiseRecoverable(i.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===i.params[0].type&&this.raiseRecoverable(i.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},X.parseClassField=function(e){if(te(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&te(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(b.eq)){var t=this.currentThisScope(),s=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=s}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},X.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==b.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},X.parseClassId=function(e,t){this.type===b.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},X.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts(null,!1):null},X.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},X.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,n=0===r?null:this.privateNameStack[r-1],i=0;i=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},X.parseExport=function(e,t){if(this.next(),this.eat(b.star))return this.parseExportAllDeclaration(e,t);if(this.eat(b._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==b.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,r=e.specifiers;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},X.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},X.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},X.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===b.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(b.comma)))return e;if(this.type===b.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(b.braceL);!this.eat(b.braceR);){if(t)t=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;e.push(this.parseImportSpecifier())}return e},X.parseWithClause=function(){var e=[];if(!this.eat(b._with))return e;this.expect(b.braceL);for(var t={},s=!0;!this.eat(b.braceR);){if(s)s=!1;else if(this.expect(b.comma),this.afterTrailingComma(b.braceR))break;var r=this.parseImportAttribute(),n="Identifier"===r.key.type?r.key.name:r.key.value;C(t,n)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(r)}return e},X.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(b.colon),this.type!==b.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===b.string){var e=this.parseLiteral(this.value);return R.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},X.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var se=U.prototype;se.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var r=0,n=e.properties;r=8&&!o&&"async"===u.name&&!this.canInsertSemicolon()&&this.eat(b._function))return this.overrideContext(ne.f_expr),this.parseFunction(this.startNodeAt(i,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(b.arrow))return this.parseArrowExpression(this.startNodeAt(i,a),[u],!1,t);if(this.options.ecmaVersion>=8&&"async"===u.name&&this.type===b.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return u=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(b.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,a),[u],!0,t)}return u;case b.regexp:var l=this.value;return(r=this.parseLiteral(l.value)).regex={pattern:l.pattern,flags:l.flags},r;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:return(r=this.startNode()).value=this.type===b._null?null:this.type===b._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case b.parenL:var h=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),c;case b.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(b.bracketR,!0,!0,e),this.finishNode(r,"ArrayExpression");case b.braceL:return this.overrideContext(ne.b_expr),this.parseObj(!1,e);case b._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case b._class:return this.parseClass(this.startNode(),!1);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}},ae.parseExprAtomDefault=function(){this.unexpected()},ae.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===b.parenL&&!e)return this.parseDynamicImport(t);if(this.type===b.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},ae.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(b.parenR)?e.options=null:(this.expect(b.comma),this.afterTrailingComma(b.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(b.parenR)||(this.expect(b.comma),this.afterTrailingComma(b.parenR)||this.unexpected())));else if(!this.eat(b.parenR)){var t=this.start;this.eat(b.comma)&&this.eat(b.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},ae.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},ae.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();return this.expect(b.parenR),e},ae.shouldParseArrow=function(e){return!this.canInsertSemicolon()},ae.parseParenAndDistinguishExpression=function(e,t){var s,r=this.start,n=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,u=this.startLoc,l=[],h=!0,c=!1,p=new q,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==b.parenR;){if(h?h=!1:this.expect(b.comma),i&&this.afterTrailingComma(b.parenR,!0)){c=!0;break}if(this.type===b.ellipsis){a=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}l.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(b.parenR),e&&this.shouldParseArrow(l)&&this.eat(b.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(r,n,l,t);l.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,l.length>1?((s=this.startNodeAt(o,u)).expressions=l,this.finishNodeAt(s,"SequenceExpression",m,g)):s=l[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(r,n);return y.expression=s,this.finishNode(y,"ParenthesizedExpression")}return s},ae.parseParenItem=function(e){return e},ae.parseParenArrowList=function(e,t,s,r){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,r)};var le=[];ae.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===b.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var r=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,n,!0,!1),this.eat(b.parenL)?e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,!1):e.arguments=le,this.finishNode(e,"NewExpression")},ae.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===b.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===b.backQuote,this.finishNode(s,"TemplateElement")},ae.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(s.quasis=[r];!r.tail;)this.type===b.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(b.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(b.braceR),s.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},ae.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))},ae.parseObj=function(e,t){var s=this.startNode(),r=!0,n={};for(s.properties=[],this.next();!this.eat(b.braceR);){if(r)r=!1;else if(this.expect(b.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR))break;var i=this.parseProperty(e,t);e||this.checkPropClash(i,n,t),s.properties.push(i)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},ae.parseProperty=function(e,t){var s,r,n,i,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===b.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===b.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,i=this.startLoc),e||(s=this.eat(b.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(r=!0,s=this.options.ecmaVersion>=9&&this.eat(b.star),this.parsePropertyName(a)):r=!1,this.parsePropertyValue(a,e,s,r,n,i,t,o),this.finishNode(a,"Property")},ae.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},ae.parsePropertyValue=function(e,t,s,r,n,i,a,o){(s||r)&&this.type===b.colon&&this.unexpected(),this.eat(b.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===b.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(s,r)):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===b.comma||this.type===b.braceR||this.type===b.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||r)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key)):this.type===b.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,i,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((s||r)&&this.unexpected(),this.parseGetterSetter(e))},ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(b.bracketR),e.key;e.computed=!1}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},ae.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ae.parseMethod=function(e,t,s){var r=this.startNode(),n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|z(t,r.generator)|(s?128:0)),this.expect(b.parenL),r.params=this.parseBindingList(b.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")},ae.parseArrowExpression=function(e,t,s,r){var n=this.yieldPos,i=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|z(s,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=n,this.awaitPos=i,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},ae.parseFunctionBody=function(e,t,s,r){var n=t&&this.type!==b.braceL,i=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);i&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var u=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!i&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!i),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=u}this.exitScope()},ae.isSimpleParamList=function(e){for(var t=0,s=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t)this.currentScope().lexical.push(e);else if(3===t){var i=this.currentScope();r=this.treatFunctionsAsVar?i.lexical.indexOf(e)>-1:i.lexical.indexOf(e)>-1||i.var.indexOf(e)>-1,i.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){r=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],259&o.flags)break}r&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},ce.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},ce.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},ce.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},ce.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var de=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new M(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fe=U.prototype;function me(e,t,s,r){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=s),e}fe.startNode=function(){return new de(this,this.start,this.startLoc)},fe.startNodeAt=function(e,t){return new de(this,e,t)},fe.finishNode=function(e,t){return me.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fe.finishNodeAt=function(e,t,s,r){return me.call(this,e,t,s,r)},fe.copyNode=function(e){var t=new de(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var ge="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",ye=ge+" Extended_Pictographic",xe=ye+" EBase EComp EMod EPres ExtPict",be={9:ge,10:ye,11:ye,12:xe,13:xe,14:xe},ve={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Se="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Te="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Ae=Te+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",we=Ae+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",_e=we+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ee=_e+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Ie={9:Te,10:Ae,11:we,12:_e,13:Ee,14:Ee+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},ke={};function Ce(e){var t=ke[e]={binary:F(be[e]+" "+Se),binaryOfStrings:F(ve[e]),nonBinary:{General_Category:F(Se),Script:F(Ie[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Le=0,De=[9,10,11,12,13,14];Le=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=ke[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Ne(e){return 105===e||109===e||115===e}function Me(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Ge(e){return e>=65&&e<=90||e>=97&&e<=122}function Oe(e){return Ge(e)||95===e}function Ve(e){return Oe(e)||Pe(e)}function Pe(e){return e>=48&&e<=57}function Be(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ze(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Ue(e){return e>=48&&e<=55}Re.prototype.reset=function(e,t,s){var r=-1!==s.indexOf("v"),n=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Re.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Re.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return-1;var n=s.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=r)return n;var i=s.charCodeAt(e+1);return i>=56320&&i<=57343?(n<<10)+i-56613888:n},Re.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,r=s.length;if(e>=r)return r;var n,i=s.charCodeAt(e);return!t&&!this.switchU||i<=55295||i>=57344||e+1>=r||(n=s.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Re.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Re.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Re.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Re.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Re.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,r=0,n=e;r-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(r=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&r&&n&&this.raise(e.start,"Invalid regular expression flag")},Fe.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Fe.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t=16;for(t&&(e.branchID=new $e(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Fe.regexp_alternative=function(e){for(;e.pos=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},Fe.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Fe.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Fe.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var r=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var s=this.regexp_eatModifiers(e),r=e.eat(45);if(s||r){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(e);s||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||s.indexOf(u)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Fe.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Fe.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&Ne(s);)t+=$(s),e.advance();return t},Fe.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Fe.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Fe.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Me(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!Me(s);)e.advance();return e.pos!==t},Fe.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t||(e.advance(),0))},Fe.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var r=0,n=s;r=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return c(e,!0)||36===e||95===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,r=e.current(s);return e.advance(s),92===r&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(r=e.lastIntValue),function(e){return p(e,!0)||36===e||95===e||8204===e||8205===e}(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)},Fe.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Fe.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},Fe.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Fe.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Fe.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Fe.regexp_eatZero=function(e){return 48===e.current()&&!Pe(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Fe.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Fe.regexp_eatControlLetter=function(e){var t=e.current();return!!Ge(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Fe.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s,r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(i-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&(s=e.lastIntValue)>=0&&s<=1114111)return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1},Fe.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t||(e.lastIntValue=t,e.advance(),0))},Fe.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1},Fe.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var r;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&2===r&&e.raise("Invalid property name"),r;e.raise("Invalid property name")}return 0},Fe.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,r),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Fe.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){C(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},Fe.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Fe.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Oe(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ve(t=e.current());)e.lastStringValue+=$(t),e.advance();return""!==e.lastStringValue},Fe.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Fe.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===s&&e.raise("Negated character class may contain strings"),!0}return!1},Fe.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Fe.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;!e.switchU||-1!==t&&-1!==s||e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},Fe.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Ue(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var r=e.current();return 93!==r&&(e.lastIntValue=r,e.advance(),!0)},Fe.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Fe.regexp_classSetExpression=function(e){var t,s=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(s=2);for(var r=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(s=1):e.raise("Invalid character in character class");if(r!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(r!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;2===t&&(s=2)}},Fe.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return-1!==s&&-1!==r&&s>r&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Fe.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Fe.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return s&&2===r&&e.raise("Negated character class may contain strings"),r;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Fe.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},Fe.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Fe.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Fe.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e)&&(e.eat(98)?(e.lastIntValue=8,0):(e.pos=t,1)));var s=e.current();return!(s<0||s===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(s)||function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(s)||(e.advance(),e.lastIntValue=s,0))},Fe.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Fe.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!Pe(t)&&95!==t||(e.lastIntValue=t%32,e.advance(),0))},Fe.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Fe.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Pe(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},Fe.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Be(s=e.current());)e.lastIntValue=16*e.lastIntValue+ze(s),e.advance();return e.pos!==t},Fe.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},Fe.regexp_eatOctalDigit=function(e){var t=e.current();return Ue(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Fe.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var r=0;r=this.input.length?this.finishToken(b.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},We.readToken=function(e){return c(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},We.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},We.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var r=void 0,n=t;(r=A(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},We.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&w.test(String.fromCharCode(e))))break e;++this.pos}}},We.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},We.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(b.ellipsis)):(++this.pos,this.finishToken(b.dot))},We.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(b.assign,2):this.finishOp(b.slash,1)},We.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,r=42===e?b.star:b.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,r=b.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(b.assign,s+1):this.finishOp(r,s)},We.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(124===e?b.logicalOR:b.logicalAND,2):61===t?this.finishOp(b.assign,2):this.finishOp(124===e?b.bitwiseOR:b.bitwiseAND,1)},We.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(b.assign,2):this.finishOp(b.bitwiseXOR,1)},We.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!v.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(b.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(b.assign,2):this.finishOp(b.plusMin,1)},We.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(b.assign,s+1):this.finishOp(b.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(b.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},We.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(b.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(b.arrow)):this.finishOp(61===e?b.eq:b.prefix,1)},We.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(b.questionDot,2)}if(63===t)return e>=12&&61===this.input.charCodeAt(this.pos+2)?this.finishOp(b.assign,3):this.finishOp(b.coalesce,2)}return this.finishOp(b.question,1)},We.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,c(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(b.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(b.parenL);case 41:return++this.pos,this.finishToken(b.parenR);case 59:return++this.pos,this.finishToken(b.semi);case 44:return++this.pos,this.finishToken(b.comma);case 91:return++this.pos,this.finishToken(b.bracketL);case 93:return++this.pos,this.finishToken(b.bracketR);case 123:return++this.pos,this.finishToken(b.braceL);case 125:return++this.pos,this.finishToken(b.braceR);case 58:return++this.pos,this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+$(e)+"'")},We.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},We.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(v.test(r)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===r)t=!0;else if("]"===r&&t)t=!1;else if("/"===r&&!t)break;e="\\"===r}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var i=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new Re(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var u=null;try{u=new RegExp(n,a)}catch(e){}return this.finishToken(b.regexp,{pattern:n,flags:a,value:u})},We.readInt=function(e,t,s){for(var r=this.options.ecmaVersion>=12&&void 0===t,n=s&&48===this.input.charCodeAt(this.pos),i=this.pos,a=0,o=0,u=0,l=null==t?1/0:t;u=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+c}}return r&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===i||null!=t&&this.pos-i!==t?null:a},We.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=je(this.input.slice(t,this.pos)),++this.pos):c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,s)},We.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===r){var n=je(this.input.slice(t,this.pos));return++this.pos,c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(b.num,n)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46!==r||s||(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),69!==r&&101!==r||s||(43!==(r=this.input.charCodeAt(++this.pos))&&45!==r||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),c(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var i,a=(i=this.input.slice(t,this.pos),s?parseInt(i,8):parseFloat(i.replace(/_/g,"")));return this.finishToken(b.num,a)},We.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},We.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===r||8233===r?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(T(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(b.string,t)};var qe={};We.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==qe)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},We.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw qe;this.raise(e,t)},We.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==b.template&&this.type!==b.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(b.template,e)):36===s?(this.pos+=2,this.finishToken(b.dollarBraceL)):(++this.pos,this.finishToken(b.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(T(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},We.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),"0"===r&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-r.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return T(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},We.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},We.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,r=this.options.ecmaVersion>=6;this.pos{var s=class{constructor(e,t){this.value=e,Array.isArray(t)?this.size=t:(this.size=new Int32Array(3),t.z?this.size=new Int32Array([t.x,t.y,t.z]):t.y?this.size=new Int32Array([t.x,t.y]):this.size=new Int32Array([t.x]));const[s,r,n]=this.size;if(n){if(this.value.length!==s*r*n)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} * ${n} = ${r*s*n}`)}else if(r){if(this.value.length!==s*r)throw new Error(`Input size ${this.value.length} does not match ${s} * ${r} = ${r*s}`)}else if(this.value.length!==s)throw new Error(`Input size ${this.value.length} does not match ${s}`)}toArray(){const{utils:e}=i(),[t,s,r]=this.size;return r?e.erectMemoryOptimized3DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s,r):s?e.erectMemoryOptimized2DFloat(this.value.subarray?this.value:new Float32Array(this.value),t,s):this.value}};t.exports={Input:s,input:function(e,t){return new s(e,t)}}}),n=e((e,t)=>{t.exports={Texture:class{constructor(e){const{texture:t,size:s,dimensions:r,output:n,context:i,type:a="NumberTexture",kernel:o,internalFormat:u,textureFormat:l}=e;if(!n)throw new Error('settings property "output" required.');if(!i)throw new Error('settings property "context" required.');if(!t)throw new Error('settings property "texture" required.');if(!o)throw new Error('settings property "kernel" required.');this.texture=t,t._refs?t._refs++:t._refs=1,this.size=s,this.dimensions=r,this.output=n,this.context=i,this.kernel=o,this.type=a,this._deleted=!1,this.internalFormat=u,this.textureFormat=l}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}}}),i=e((e,t)=>{const i=s(),{Input:a}=r(),{Texture:o}=n(),u=/function ([^(]*)/,l=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,h=/([^\s,]+)/g,c={systemEndianness:()=>m,getSystemEndianness(){const e=new ArrayBuffer(4),t=new Uint32Array(e),s=new Uint8Array(e);if(t[0]=3735928559,239===s[0])return"LE";if(222===s[0])return"BE";throw new Error("unknown endianness")},isFunction:e=>"function"==typeof e,isFunctionString:e=>"string"==typeof e&&"function"===e.slice(0,8).toLowerCase(),getFunctionNameFromString(e){const t=u.exec(e);return t&&0!==t.length?t[1].trim():null},getFunctionBodyFromString:e=>e.substring(e.indexOf("{")+1,e.lastIndexOf("}")),getArgumentNamesFromString(e){const t=e.replace(l,"");let s=t.slice(t.indexOf("(")+1,t.indexOf(")")).match(h);return null===s&&(s=[]),s},clone(e){if(null===e||"object"!=typeof e||e.hasOwnProperty("isActiveClone"))return e;const t=e.constructor();for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e.isActiveClone=null,t[s]=c.clone(e[s]),delete e.isActiveClone);return t},isArray:e=>!isNaN(e.length),typeFitsValue(e,t){if("string"!=typeof e||null==t)return!0;if(t.type)return!0;switch(e){case"Input":return t instanceof a;case"Boolean":return"boolean"==typeof t;case"Number":case"Integer":case"Float":return"number"==typeof t}return-1!==e.indexOf("Texture")?Boolean(t.type):0!==e.indexOf("Array")||c.isArray(t)},getVariableType(e,t){if(c.isArray(e))return e.length>0&&"IMG"===e[0].nodeName?"HTMLImageArray":"Array";switch(e.constructor){case Boolean:return"Boolean";case Number:return t&&Number.isInteger(e)?"Integer":"Float";case o:return e.type;case a:return"Input"}if("nodeName"in e)switch(e.nodeName){case"IMG":case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}else{if(e.hasOwnProperty("type"))return e.type;if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return"OffscreenCanvas";if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return"ImageBitmap";if("undefined"!=typeof ImageData&&e instanceof ImageData)return"ImageData"}return"Unknown"},getKernelTextureSize(e,t){let[s,r,n]=t,i=(s||1)*(r||1)*(n||1);return e.optimizeFloatMemory&&"single"===e.precision&&(s=i=Math.ceil(i/4)),r>1&&s*r===i?new Int32Array([s,r]):c.closestSquareDimensions(i)},closestSquareDimensions(e){const t=Math.sqrt(e);let s=Math.ceil(t),r=Math.floor(t);for(;s*rMath.floor((e+t-1)/t)*t,getDimensions(e,t){let s;if(c.isArray(e)){const t=[];let r=e;for(;c.isArray(r);)t.push(r.length),r=r[0];s=t.reverse()}else if(e instanceof o)s=e.output;else{if(!(e instanceof a))throw new Error(`Unknown dimensions of ${e}`);s=e.size}if(t)for(s=Array.from(s);s.length<3;)s.push(1);return new Int32Array(s)},flatten2dArrayTo(e,t){let s=0;for(let r=0;re.length>0?e.join(";\n")+";\n":"\n",warnDeprecated(e,t,s){s?console.warn(`You are using a deprecated ${e} "${t}". It has been replaced with "${s}". Fixing, but please upgrade as it will soon be removed.`):console.warn(`You are using a deprecated ${e} "${t}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)},flipPixels:(e,t,s)=>{const r=s/2|0,n=4*t,i=new Uint8ClampedArray(4*t),a=e.slice(0);for(let e=0;ee.subarray(0,t),erect2DPackedFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;ie.subarray(0,t),erectMemoryOptimized2DFloat:(e,t,s)=>{const r=new Array(s);for(let n=0;n{const n=new Array(r);for(let i=0;i{const s=new Float32Array(t);let r=0;for(let n=0;n{const r=new Array(s);let n=0;for(let i=0;i{const n=new Array(r);let i=0;for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=new Array(s),n=4*t;for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(t),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const s=new Array(e),r=4*t;let n=0;for(let t=0;t{const r=4*t,n=new Array(s);for(let i=0;i{const n=4*t,i=new Array(r);for(let a=0;a{const{findDependency:s,thisLookup:r,doNotDefine:n}=t;let a=t.flattened;a||(a=t.flattened={});const o=i.parse(e,{ecmaVersion:2020}),u=[];let l=0;const h=function e(t){if(Array.isArray(t)){const s=[];for(let r=0;rnull!==e);return n.length<1?"":`${t.kind} ${n.join(",")}`;case"VariableDeclarator":return t.init?t.init.object&&"ThisExpression"===t.init.object.type?r(t.init.property.name,!0)?`${t.id.name} = ${e(t.init)}`:null:`${t.id.name} = ${e(t.init)}`:t.id.name;case"CallExpression":if("subarray"===t.callee.property.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("gl"===t.callee.object.name||"context"===t.callee.object.name)return`${e(t.callee.object)}.${e(t.callee.property)}(${t.arguments.map(t=>e(t)).join(", ")})`;if("ThisExpression"===t.callee.object.type)return u.push(s("this",t.callee.property.name)),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;if(t.callee.object.name){const r=s(t.callee.object.name,t.callee.property.name);return null===r?`${t.callee.object.name}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`:(u.push(r),`${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`)}if("MemberExpression"===t.callee.object.type)return`${e(t.callee.object)}.${t.callee.property.name}(${t.arguments.map(t=>e(t)).join(", ")})`;throw new Error("unknown ast.callee");case"ReturnStatement":return`return ${e(t.argument)}`;case"BinaryExpression":return`(${e(t.left)}${t.operator}${e(t.right)})`;case"UnaryExpression":return t.prefix?`${t.operator} ${e(t.argument)}`:`${e(t.argument)} ${t.operator}`;case"ExpressionStatement":return`${e(t.expression)}`;case"SequenceExpression":return`(${e(t.expressions)})`;case"ArrowFunctionExpression":return`(${t.params.map(e).join(", ")}) => ${e(t.body)}`;case"Literal":return t.raw;case"Identifier":return t.name;case"MemberExpression":return"ThisExpression"===t.object.type?r(t.property.name):t.computed?`${e(t.object)}[${e(t.property)}]`:e(t.object)+"."+e(t.property);case"ThisExpression":return"this";case"NewExpression":return`new ${e(t.callee)}(${t.arguments.map(t=>e(t)).join(", ")})`;case"ForStatement":return`for (${e(t.init)};${e(t.test)};${e(t.update)}) ${e(t.body)}`;case"AssignmentExpression":return`${e(t.left)}${t.operator}${e(t.right)}`;case"UpdateExpression":return`${e(t.argument)}${t.operator}`;case"IfStatement":{const s=e(t.consequent);if(!t.alternate)return`if (${e(t.test)}) ${s}`;const r="BlockStatement"===t.consequent.type?"":";";return`if (${e(t.test)}) ${s}${r} else ${e(t.alternate)}`}case"ThrowStatement":return`throw ${e(t.argument)}`;case"ObjectPattern":return t.properties.map(e).join(", ");case"ArrayPattern":return t.elements.map(e).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${e(t.test)}?${e(t.consequent)}:${e(t.alternate)}`;case"Property":if("init"===t.kind)return e(t.key)}throw new Error(`unhandled ast.type of ${t.type}`)}(o);if(u.length>0){const e=[];for(let s=0;s{if("VariableDeclaration"!==e.type)throw new Error('Ast is not of type "VariableDeclaration"');const t=[];for(let s=0;s{const s=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].r},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),r=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].g},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),n=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].b},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),i=e.createKernel(function(e){return 255*e[this.thread.y][this.thread.x].a},{output:[t.width,t.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}}),a=[s(t),r(t),n(t),i(t)];return a.rKernel=s,a.gKernel=r,a.bKernel=n,a.aKernel=i,a.gpu=e,a},splitRGBAToCanvases:(e,t,s,r)=>{const n=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(t.r/255,0,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});n(t);const i=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,t.g/255,0,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});i(t);const a=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(0,0,t.b/255,255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});a(t);const o=e.createKernel(function(e){const t=e[this.thread.y][this.thread.x];this.color(255,255,255,t.a/255)},{output:[s,r],graphical:!0,argumentTypes:{v:"Array2D(4)"}});return o(t),[n.canvas,i.canvas,a.canvas,o.canvas]},getMinifySafeName:e=>{try{const{init:t}=i.parse(`const value = ${e.toString()}`,{ecmaVersion:2020}).body[0].declarations[0];return t.body.name||t.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(e){return p.test(e)&&(e=e.replace(p,"S_S")),d.test(e)?e=e.replace(d,"U_U"):f.test(e)&&(e=e.replace(f,"u_u")),e}},p=/\$/,d=/__/,f=/_/,m=c.getSystemEndianness();t.exports={utils:c}}),a=e((e,t)=>{const{utils:s}=i(),{Input:n}=r();t.exports={Kernel:class{static get isSupported(){throw new Error(`"isSupported" not implemented on ${this.name}`)}static isContextMatch(e){throw new Error(`"isContextMatch" not implemented on ${this.name}`)}static getFeatures(){throw new Error(`"getFeatures" not implemented on ${this.name}`)}static destroyContext(e){throw new Error(`"destroyContext" called on ${this.name}`)}static nativeFunctionArguments(){throw new Error(`"nativeFunctionArguments" called on ${this.name}`)}static nativeFunctionReturnType(){throw new Error(`"nativeFunctionReturnType" called on ${this.name}`)}static combineKernels(){throw new Error(`"combineKernels" called on ${this.name}`)}constructor(e,t){if("object"!=typeof e){if("string"!=typeof e)throw new Error("source not a string");if(!s.isFunctionString(e))throw new Error("source not a function string")}this.useLegacyEncoder=!1,this.fallbackRequested=!1,this.fallbackReason=null,this.onRequestFallback=null,this.onRequestSwitchKernel=null,this.argumentNames="string"==typeof e?s.getArgumentNamesFromString(e):null,this.argumentTypes=null,this.declaredArgumentTypes=null,this.argumentSizes=null,this.argumentBitRatios=null,this.kernelArguments=null,this.kernelConstants=null,this.forceUploadKernelConstants=null,this.source=e,this.output=null,this.debug=!1,this.graphical=!1,this.loopMaxIterations=0,this.constants=null,this.constantTypes=null,this.constantBitRatios=null,this.dynamicArguments=!1,this.dynamicOutput=!1,this.canvas=null,this.context=null,this.checkContext=null,this.gpu=null,this.functions=null,this.nativeFunctions=null,this.injectedNative=null,this.subKernels=null,this.validate=!0,this.immutable=!1,this.pipeline=!1,this.asyncMode=!1,this.precision=null,this.tactic=null,this.plugins=null,this.returnType=null,this.leadingReturnStatement=null,this.followingReturnStatement=null,this.optimizeFloatMemory=null,this.strictIntegers=!1,this.fixIntegerDivisionAccuracy=null,this.randomSeed=null,this.built=!1,this.signature=null,this.switchingKernels=null}mergeSettings(e){for(let t in e)if(e.hasOwnProperty(t)&&this.hasOwnProperty(t)){switch(t){case"argumentTypes":this.argumentTypes=e[t],e[t]&&(this.declaredArgumentTypes=Array.isArray(e[t])?e[t].slice():e[t]);continue;case"output":if(!Array.isArray(e.output)){this.setOutput(e.output);continue}break;case"functions":this.functions=[];for(let t=0;te.name):null,returnType:this.returnType}}}buildSignature(e){const t=this.constructor;this.signature=t.getSignature(this,t.getArgumentTypes(this,e))}static getArgumentTypes(e,t){const r=new Array(t.length);for(let n=0;nt.argumentTypes[e])||[];const i=Object.keys(t.argumentTypes);if(i.length>0&&e.length>0&&n.every(e=>void 0===e))throw new Error(`argumentTypes keys [${i.join(", ")}] match none of the function's parameters [${e.join(", ")}] \u2014 a bundler may have renamed them. Use the array form: argumentTypes: ['${i.map(e=>t.argumentTypes[e]).join("', '")}']`)}else n=t.argumentTypes||[];return{name:t.name||s.getFunctionNameFromString(r)||("function"==typeof e&&e.name?e.name:null),source:r,argumentTypes:n,returnType:t.returnType||null}}onActivate(e){}switchKernels(e){this.switchingKernels?this.switchingKernels.push(e):this.switchingKernels=[e]}resetSwitchingKernels(){const e=this.switchingKernels;return this.switchingKernels=null,e}checkArgumentTypes(e){if(!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let r=0;r{t.exports={FunctionBuilder:class e{static fromKernel(t,s,r){const{kernelArguments:n,kernelConstants:i,argumentNames:a,argumentSizes:o,argumentBitRatios:u,constants:l,constantBitRatios:h,debug:c,loopMaxIterations:p,nativeFunctions:d,output:f,optimizeFloatMemory:m,precision:g,plugins:y,source:x,subKernels:b,functions:v,leadingReturnStatement:S,followingReturnStatement:T,dynamicArguments:A,dynamicOutput:w}=t,_=new Array(n.length),E={};for(let e=0;ez.needsArgumentType(e,t),k=(e,t,s)=>{z.assignArgumentType(e,t,s)},C=(e,t,s)=>z.lookupReturnType(e,t,s),L=e=>z.lookupFunctionArgumentTypes(e),D=(e,t)=>z.lookupFunctionArgumentName(e,t),F=(e,t)=>z.lookupFunctionArgumentBitRatio(e,t),$=(e,t,s,r)=>{z.assignArgumentType(e,t,s,r)},R=(e,t,s,r)=>{z.assignArgumentBitRatio(e,t,s,r)},N=(e,t,s)=>{z.trackFunctionCall(e,t,s)},M=(e,t)=>{const r=[];for(let t=0;tnew s(e.source,{name:e.name||void 0,returnType:e.returnType,argumentTypes:e.argumentTypes,output:f,plugins:y,constants:l,constantTypes:E,constantBitRatios:h,optimizeFloatMemory:m,precision:g,lookupReturnType:C,lookupFunctionArgumentTypes:L,lookupFunctionArgumentName:D,lookupFunctionArgumentBitRatio:F,needsArgumentType:I,assignArgumentType:k,triggerImplyArgumentType:$,triggerImplyArgumentBitRatio:R,onFunctionCall:N,onNestedFunction:M})));let B=null;b&&(B=b.map(e=>{const{name:t,source:r}=e;return new s(r,Object.assign({},G,{name:t,isSubKernel:!0,isRootKernel:!1}))}));const z=new e({kernel:t,rootNode:V,functionNodes:P,nativeFunctions:d,subKernelNodes:B});return z}constructor(e){if(e=e||{},this.kernel=e.kernel,this.rootNode=e.rootNode,this.functionNodes=e.functionNodes||[],this.subKernelNodes=e.subKernelNodes||[],this.nativeFunctions=e.nativeFunctions||[],this.functionMap={},this.nativeFunctionNames=[],this.lookupChain=[],this.functionNodeDependencies={},this.functionCalls={},this.rootNode&&(this.functionMap.kernel=this.rootNode),this.functionNodes)for(let e=0;e-1){const s=t.indexOf(e);if(-1===s)t.push(e);else{const e=t.splice(s,1)[0];t.push(e)}return t}const s=this.functionMap[e];if(s){const r=t.indexOf(e);if(-1===r){t.push(e),s.toString();for(let e=0;e-1){t.push(this.nativeFunctions[n].source);continue}const i=this.functionMap[r];i&&t.push(i.toString())}return t}toJSON(){return this.traceFunctionCalls(this.rootNode.name).reverse().map(e=>{const t=this.nativeFunctions.indexOf(e);if(t>-1)return{name:e,source:this.nativeFunctions[t].source};if(this.functionMap[e])return this.functionMap[e].toJSON();throw new Error(`function ${e} not found`)})}fromJSON(e,t){this.functionMap={};for(let s=0;s0){const n=t.arguments;for(let t=0;t{const{utils:s}=i();function r(e){return e.length>0?e[e.length-1]:null}const n="trackIdentifiers",a="memberExpression",o="inForLoopInit";t.exports={FunctionTracer:class{constructor(e){this.runningContexts=[],this.functionContexts=[],this.contexts=[],this.functionCalls=[],this.declarations=[],this.identifiers=[],this.functions=[],this.returnStatements=[],this.trackedIdentifiers=null,this.states=[],this.newFunctionContext(),this.scan(e)}isState(e){return this.states[this.states.length-1]===e}hasState(e){return this.states.indexOf(e)>-1}pushState(e){this.states.push(e)}popState(e){if(!this.isState(e))throw new Error(`Cannot pop the non-active state "${e}"`);this.states.pop()}get currentFunctionContext(){return r(this.functionContexts)}get currentContext(){return r(this.runningContexts)}newFunctionContext(){const e={"@contextType":"function"};this.contexts.push(e),this.functionContexts.push(e)}newContext(e){const t=Object.assign({"@contextType":"const/let"},this.currentContext);this.contexts.push(t),this.runningContexts.push(t),e();const{currentFunctionContext:s}=this;for(const e in s)s.hasOwnProperty(e)&&!t.hasOwnProperty(e)&&(t[e]=s[e]);return this.runningContexts.pop(),t}useFunctionContext(e){const t=r(this.functionContexts);this.runningContexts.push(t),e(),this.runningContexts.pop()}getIdentifiers(e){const t=this.trackedIdentifiers=[];return this.pushState(n),e(),this.trackedIdentifiers=null,this.popState(n),t}getDeclaration(e){const{currentContext:t,currentFunctionContext:s,runningContexts:r}=this,n=t[e]||s[e]||null;if(!n&&t===s&&r.length>0){const t=r[r.length-2];if(t[e])return t[e]}return n}scan(e){if(e)if(Array.isArray(e))for(let t=0;t{this.scan(e.body)});break;case"BlockStatement":this.newContext(()=>{this.scan(e.body)});break;case"AssignmentExpression":case"LogicalExpression":case"BinaryExpression":this.scan(e.left),this.scan(e.right);break;case"UpdateExpression":if("++"===e.operator){const t=this.getDeclaration(e.argument.name);t&&(t.suggestedType="Integer")}this.scan(e.argument);break;case"UnaryExpression":this.scan(e.argument);break;case"VariableDeclaration":"var"===e.kind?this.useFunctionContext(()=>{e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations)}):(e.declarations=s.normalizeDeclarations(e),this.scan(e.declarations));break;case"VariableDeclarator":{const{currentContext:t}=this,s=this.hasState(o),r={ast:e,context:t,name:e.id.name,origin:"declaration",inForLoopInit:s,inForLoopTest:null,assignable:t===this.currentFunctionContext||!s&&!t.hasOwnProperty(e.id.name),suggestedType:null,valueType:null,dependencies:null,isSafe:null};t[e.id.name]||(t[e.id.name]=r),this.declarations.push(r),this.scan(e.id),this.scan(e.init);break}case"FunctionExpression":case"FunctionDeclaration":0===this.runningContexts.length?this.scan(e.body):this.functions.push(e);break;case"IfStatement":this.scan(e.test),this.scan(e.consequent),e.alternate&&this.scan(e.alternate);break;case"ForStatement":{let t;const s=this.newContext(()=>{this.pushState(o),this.scan(e.init),this.popState(o),t=this.getIdentifiers(()=>{this.scan(e.test)}),this.scan(e.update),this.newContext(()=>{this.scan(e.body)})});if(t)for(const e in s)"@contextType"!==e&&t.indexOf(e)>-1&&(s[e].inForLoopTest=!0);break}case"DoWhileStatement":case"WhileStatement":this.newContext(()=>{this.scan(e.body),this.scan(e.test)});break;case"Identifier":this.isState(n)&&this.trackedIdentifiers.push(e.name),this.identifiers.push({context:this.currentContext,declaration:this.getDeclaration(e.name),ast:e});break;case"ReturnStatement":this.returnStatements.push(e),this.scan(e.argument);break;case"MemberExpression":this.pushState(a),this.scan(e.object),this.scan(e.property),this.popState(a);break;case"ExpressionStatement":this.scan(e.expression);break;case"SequenceExpression":this.scan(e.expressions);break;case"CallExpression":this.functionCalls.push({context:this.currentContext,ast:e}),this.scan(e.arguments);break;case"ArrayExpression":this.scan(e.elements);break;case"ConditionalExpression":this.scan(e.test),this.scan(e.alternate),this.scan(e.consequent);break;case"SwitchStatement":this.scan(e.discriminant),this.scan(e.cases);break;case"SwitchCase":this.scan(e.test),this.scan(e.consequent);break;case"ThisExpression":case"Literal":case"DebuggerStatement":case"EmptyStatement":case"BreakStatement":case"ContinueStatement":break;default:throw new Error(`unhandled type "${e.type}"`)}}}}}),l=e((e,t)=>{const r=s(),{utils:n}=i(),{FunctionTracer:a}=u(),o=["E","PI","SQRT2","SQRT1_2","LN2","LN10","LOG2E","LOG10E"],l=["abs","acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","ceil","clz32","cos","cosh","expm1","exp","floor","fround","imul","log","log2","log10","log1p","max","min","pow","random","round","sign","sin","sinh","sqrt","tan","tanh","trunc"],h=["value","value[]","value[][]","value[][][]","value[][][][]","value.value","value.thread.value","this.thread.value","this.output.value","this.constants.value","this.constants.value[]","this.constants.value[][]","this.constants.value[][][]","this.constants.value[][][][]","fn()[]","fn()[][]","fn()[][][]","[][]"];const c={Number:"Number",Float:"Float",Integer:"Integer",Array:"Number","Array(2)":"Number","Array(3)":"Number","Array(4)":"Number","Matrix(2)":"Number","Matrix(3)":"Number","Matrix(4)":"Number",Array2D:"Number",Array3D:"Number",Input:"Number",HTMLCanvas:"Array(4)",OffscreenCanvas:"Array(4)",HTMLImage:"Array(4)",ImageBitmap:"Array(4)",ImageData:"Array(4)",HTMLVideo:"Array(4)",HTMLImageArray:"Array(4)",NumberTexture:"Number",MemoryOptimizedNumberTexture:"Number","Array1D(2)":"Array(2)","Array1D(3)":"Array(3)","Array1D(4)":"Array(4)","Array2D(2)":"Array(2)","Array2D(3)":"Array(3)","Array2D(4)":"Array(4)","Array3D(2)":"Array(2)","Array3D(3)":"Array(3)","Array3D(4)":"Array(4)","ArrayTexture(1)":"Number","ArrayTexture(2)":"Array(2)","ArrayTexture(3)":"Array(3)","ArrayTexture(4)":"Array(4)"};let p=536870912;function d(e,t){return e.start=p++,e.end=p++,t&&t.loc&&(e.loc=t.loc),e}function f(e,t){return e&&e.body&&"BlockStatement"===e.body.type?(m(e.body,t),e):e}function m(e,t){e.body=g(e.body,t)}function g(e,t){const s=[];for(let r=0;r{if(!e||"object"!=typeof e||s)return e;if(Array.isArray(e))return e.map(r);switch(e.type){case"ContinueStatement":return e.label?(s=!0,e):d({type:"BlockStatement",body:[...T(t),e]},e);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":default:return e;case"IfStatement":return e.consequent=r(e.consequent),e.alternate&&(e.alternate=r(e.alternate)),e;case"BlockStatement":return e.body=e.body.map(r),e;case"SwitchStatement":for(let t=0;t0?(s.push(e),s):[e]}case"WhileStatement":case"DoWhileStatement":return e.body&&(e.body=x(e.body,t)),[e];case"SwitchStatement":for(let s=0;s0&&this.argumentTypes.length!==this.argumentNames.length)throw new Error(`argumentTypes count of ${this.argumentTypes.length} exceeds ${this.argumentNames.length}`);if(this.output.length<1)throw new Error("this.output is not big enough")}isIdentifierConstant(e){return!!this.constants&&this.constants.hasOwnProperty(e)}isInput(e){return"Input"===this.argumentTypes[this.argumentNames.indexOf(e)]}pushState(e){this.states.push(e)}popState(e){if(this.state!==e)throw new Error(`Cannot popState ${e} when in ${this.state}`);this.states.pop()}isState(e){return this.state===e}get state(){return this.states[this.states.length-1]}astMemberExpressionUnroll(e){if("Identifier"===e.type)return e.name;if("ThisExpression"===e.type)return"this";if("MemberExpression"===e.type&&e.object&&e.property)return e.object.hasOwnProperty("name")&&"Math"!==e.object.name?this.astMemberExpressionUnroll(e.property):this.astMemberExpressionUnroll(e.object)+"."+this.astMemberExpressionUnroll(e.property);if(e.hasOwnProperty("expressions")){const t=e.expressions[0];if("Literal"===t.type&&0===t.value&&2===e.expressions.length)return this.astMemberExpressionUnroll(e.expressions[1])}throw this.astErrorOutput("Unknown astMemberExpressionUnroll",e)}get requiresSequenceFreeForInit(){return!1}getJsAST(e){if(this.ast)return this.ast;if("object"==typeof this.source)return f(this.source,this.requiresSequenceFreeForInit),this.traceFunctionAST(this.source),this.ast=this.source;if(null===(e=e||r))throw new Error("Missing JS to AST parser");const t=Object.freeze(e.parse(`const parser_${this.name} = ${this.source};`,{locations:!0,ecmaVersion:2020})),s=t.body[0].declarations[0].init;if(f(s,this.requiresSequenceFreeForInit),this.traceFunctionAST(s),!t)throw new Error("Failed to parse JS code");return this.ast=s}getAssignedArguments(){if(this._assignedArguments)return this._assignedArguments;const e=new Set,t=new Set,s=this.argumentNames||[],r=n=>{if(n&&"object"==typeof n)if(Array.isArray(n))for(const e of n)r(e);else{"AssignmentExpression"===n.type&&"Identifier"===n.left.type&&-1!==s.indexOf(n.left.name)&&e.add(n.left.name),"UpdateExpression"===n.type&&"Identifier"===n.argument.type&&-1!==s.indexOf(n.argument.name)&&e.add(n.argument.name),"VariableDeclarator"===n.type&&"Identifier"===n.id.type&&-1!==s.indexOf(n.id.name)&&t.add(n.id.name);for(const e in n){if("loc"===e||"range"===e||"parent"===e)continue;const t=n[e];t&&"object"==typeof t&&r(t)}}};r(this.getJsAST());for(const s of t)e.delete(s);return this._assignedArguments=e}traceFunctionAST(e){const{contexts:t,declarations:s,functions:r,identifiers:n,functionCalls:i}=new a(e);this.contexts=t,this.identifiers=n,this.functionCalls=i,this.functions=r;for(let e=0;e":case"<":return"Boolean";case"&":case"|":case"^":case"<<":case">>":case">>>":return"Integer"}const s=this.getType(e.left);if(this.isState("skip-literal-correction"))return s;if("LiteralInteger"===s){const t=this.getType(e.right);return"LiteralInteger"===t?e.left.value%1==0?"Integer":"Float":t}if("Integer"===s){const t=this.getType(e.right);if("Number"===t||"Float"===t)return t}return c[s]||s;case"UpdateExpression":case"ReturnStatement":return this.getType(e.argument);case"UnaryExpression":return"~"===e.operator?"Integer":this.getType(e.argument);case"VariableDeclaration":{const t=e.declarations;let s;for(let e=0;ee.isSafe)}getDependencies(e,t,s){if(t||(t=[]),!e)return null;if(Array.isArray(e)){for(let r=0;r-1/0&&e.value<1/0&&!isNaN(e.value))});break;case"VariableDeclarator":return this.getDependencies(e.init,t,s);case"Identifier":const r=this.getDeclaration(e);if(r)t.push({name:e.name,origin:"declaration",isSafe:!s&&this.isSafeDependencies(r.dependencies)});else if(this.argumentNames.indexOf(e.name)>-1)t.push({name:e.name,origin:"argument",isSafe:!1});else if(this.strictTypingChecking)throw new Error(`Cannot find identifier origin "${e.name}"`);break;case"FunctionDeclaration":return this.getDependencies(e.body.body[e.body.body.length-1],t,s);case"ReturnStatement":return this.getDependencies(e.argument,t);case"BinaryExpression":case"LogicalExpression":return s="/"===e.operator||"*"===e.operator,this.getDependencies(e.left,t,s),this.getDependencies(e.right,t,s),t;case"UnaryExpression":case"UpdateExpression":return this.getDependencies(e.argument,t,s);case"VariableDeclaration":return this.getDependencies(e.declarations,t,s);case"ArrayExpression":return t.push({origin:"declaration",isSafe:!0}),t;case"CallExpression":return t.push({origin:"function",isSafe:!0}),t;case"MemberExpression":const n=this.getMemberExpressionDetails(e);switch(n.signature){case"value[]":this.getDependencies(e.object,t,s);break;case"value[][]":this.getDependencies(e.object.object,t,s);break;case"value[][][]":this.getDependencies(e.object.object.object,t,s);break;case"this.output.value":this.dynamicOutput&&t.push({name:n.name,origin:"output",isSafe:!1})}if(n)return n.property&&this.getDependencies(n.property,t,s),n.xProperty&&this.getDependencies(n.xProperty,t,s),n.yProperty&&this.getDependencies(n.yProperty,t,s),n.zProperty&&this.getDependencies(n.zProperty,t,s),t;case"SequenceExpression":return this.getDependencies(e.expressions,t,s);default:throw this.astErrorOutput(`Unhandled type ${e.type} in getDependencies`,e)}return t}getVariableSignature(e,t){if(!this.isAstVariable(e))throw new Error(`ast of type "${e.type}" is not a variable signature`);if("Identifier"===e.type)return"value";const s=[];for(;e;)e.computed?s.push("[]"):"ThisExpression"===e.type?s.unshift("this"):e.property&&e.property.name?"x"===e.property.name||"y"===e.property.name||"z"===e.property.name?s.unshift(t?"."+e.property.name:".value"):"constants"===e.property.name||"thread"===e.property.name||"output"===e.property.name?s.unshift("."+e.property.name):s.unshift(t?"."+e.property.name:".value"):e.name?s.unshift(t?e.name:"value"):e.callee&&e.callee.name?s.unshift(t?e.callee.name+"()":"fn()"):e.elements?s.unshift("[]"):s.unshift("unknown"),e=e.object;const r=s.join("");return t||h.includes(r)?r:null}build(){return this.toString().length>0}astGeneric(e,t){if(null===e)throw this.astErrorOutput("NULL ast",e);if(Array.isArray(e)){for(let s=0;s0?r[r.length-1]:0;return new Error(`${e} on line ${r.length}, position ${i.length}:\n ${s}`)}astDebuggerStatement(e,t){return t}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);return t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t}astFunction(e,t){throw new Error(`"astFunction" not defined on ${this.constructor.name}`)}astFunctionDeclaration(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}astFunctionExpression(e,t){return this.isChildFunction(e)?t:this.astFunction(e,t)}isChildFunction(e){for(let t=0;t1?t.push("(",r.join(","),")"):t.push(r[0]),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)||(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator))),t}checkAndUpconvertBitwiseUnary(e,t){}astUpdateExpression(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}astLogicalExpression(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}astMemberExpression(e,t){return t}astCallExpression(e,t){return t}astArrayExpression(e,t){return t}getMemberExpressionDetails(e){if("MemberExpression"!==e.type)throw this.astErrorOutput(`Expression ${e.type} not a MemberExpression`,e);let t=null,s=null;const r=this.getVariableSignature(e);switch(r){case"value":return null;case"value.thread.value":case"this.thread.value":case"this.output.value":return{signature:r,type:"Integer",name:e.property.name};case"value[]":if("string"!=typeof e.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object),xProperty:e.property};case"value[][]":if("string"!=typeof e.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object),yProperty:e.object.property,xProperty:e.property};case"value[][][]":if("string"!=typeof e.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value[][][][]":if("string"!=typeof e.object.object.object.object.name)throw this.astErrorOutput("Unexpected expression",e);return t=e.object.object.object.object.name,{name:t,origin:"user",signature:r,type:this.getVariableType(e.object.object.object.object),zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"value.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(this.isAstMathVariable(e))return t=e.property.name,{name:t,origin:"Math",type:"Number",signature:r};switch(e.property.name){case"r":case"g":case"b":case"a":return t=e.object.name,{name:t,property:e.property.name,origin:"user",signature:r,type:"Number"};default:throw this.astErrorOutput("Unexpected expression",e)}case"this.constants.value":if("string"!=typeof e.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r};case"this.constants.value[]":if("string"!=typeof e.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,xProperty:e.property};case"this.constants.value[][]":if("string"!=typeof e.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,yProperty:e.object.property,xProperty:e.property};case"this.constants.value[][][]":if("string"!=typeof e.object.object.object.property.name)throw this.astErrorOutput("Unexpected expression",e);if(t=e.object.object.object.property.name,s=this.getConstantType(t),!s)throw this.astErrorOutput("Constant has no type",e);return{name:t,type:s,origin:"constants",signature:r,zProperty:e.object.object.property,yProperty:e.object.property,xProperty:e.property};case"fn()[]":case"fn()[][]":case"[][]":return{signature:r,property:e.property};default:throw this.astErrorOutput("Unexpected expression",e)}}findIdentifierOrigin(e){const t=[this.ast];for(;t.length>0;){const s=t[0];if("VariableDeclarator"===s.type&&s.id&&s.id.name&&s.id.name===e.name)return s;if(t.shift(),s.argument)t.push(s.argument);else if(s.body)t.push(s.body);else if(s.declarations)t.push(s.declarations);else if(Array.isArray(s))for(let e=0;e0;){const e=t.pop();if("ReturnStatement"===e.type)return e;if("FunctionDeclaration"!==e.type)if(e.argument)t.push(e.argument);else if(e.body)t.push(e.body);else if(e.declarations)t.push(e.declarations);else if(Array.isArray(e))for(let s=0;s{const{FunctionNode:s}=l();t.exports={CPUFunctionNode:class extends s{markupUserName(e){return this.isRootKernel&&this.getAssignedArguments().has(e)?`cellShadow_user_${e}`:`user_${e}`}astFunction(e,t){if(!this.isRootKernel){t.push("function"),t.push(" "),t.push(this.name),t.push("(");for(let e=0;e0&&t.push(", "),t.push("user_"),t.push(s)}t.push(") {\n")}if(this.isRootKernel){for(const e of this.getAssignedArguments())t.push(`let cellShadow_user_${e} = user_${e};\n`);t.push("kernelBody: {\n")}for(let s=0;s0&&t.push(s.join(""),";\n"),t.push(`for (let ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);return t.push("for (let i = 0; i < LOOP_MAX; i++) {"),t.push("if ("),this.astGeneric(e.test,t),t.push(") {\n"),this.astGeneric(e.body,t),t.push("} else {\n"),t.push("break;\n"),t.push("}\n"),t.push("}\n"),t}astDoWhileStatement(e,t){if("DoWhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=`safeI${this.astKey(e,"_")}`;return t.push(`let ${s} = 0;\n`),t.push("do {"),this.astGeneric(e.body,t),t.push("} while (("),this.astGeneric(e.test,t),t.push(`) && ++${s} < LOOP_MAX);\n`),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");return s?this.popState("assignment-as-statement"):t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;s0&&t.push(",");const r=s[e],n=this.getDeclaration(r.id);n.valueType||(n.valueType=this.getType(r.init)),this.astGeneric(r,t)}return this.isState("in-for-loop-init")||t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchStatement(e,t){const{discriminant:s,cases:r}=e;t.push("switch ("),this.astGeneric(s,t),t.push(") {\n");for(let e=0;e0&&(this.astGeneric(r[e].consequent,t),t.push("break;\n"))):(t.push("default:\n"),this.astGeneric(r[e].consequent,t),r[e].consequent&&r[e].consequent.length>0&&t.push("break;\n"));t.push("\n}")}astThisExpression(e,t){return t.push("_this"),t}astMemberExpression(e,t){const{signature:s,type:r,property:n,xProperty:i,yProperty:a,zProperty:o,name:u,origin:l}=this.getMemberExpressionDetails(e);switch(s){case"this.thread.value":return t.push(`_this.thread.${u}`),t;case"this.output.value":switch(u){case"x":t.push("outputX");break;case"y":t.push("outputY");break;case"z":t.push("outputZ");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":default:throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value.value":if("Math"===l)return t.push(Math[u]),t;switch(n){case"r":return t.push(`user_${u}[0]`),t;case"g":return t.push(`user_${u}[1]`),t;case"b":return t.push(`user_${u}[2]`),t;case"a":return t.push(`user_${u}[3]`),t}break;case"this.constants.value":case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":break;case"fn()[]":return this.astGeneric(e.object,t),t.push("["),this.astGeneric(e.property,t),t.push("]"),t;case"fn()[][]":return this.astGeneric(e.object.object,t),t.push("["),this.astGeneric(e.object.property,t),t.push("]"),t.push("["),this.astGeneric(e.property,t),t.push("]"),t}if(!e.computed)switch(r){case"Number":case"Integer":case"Float":case"Boolean":return t.push("user"===l?this.markupUserName(u):`${l}_${u}`),t}const h="user"===l?this.markupUserName(u):`${l}_${u}`;{let e,s;if("constants"===l){const t=this.constants[u];s="Input"===this.constantTypes[u],e=s?t.size:null}else s=this.isInput(u),e=s?this.argumentSizes[this.argumentNames.indexOf(u)]:null;t.push(`${h}`),o&&a?s?(t.push("[("),this.astGeneric(o,t),t.push(`*${this.dynamicArguments?"(outputY * outputX)":e[1]*e[0]})+(`),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(o,t),t.push("]"),t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):a?s?(t.push("[("),this.astGeneric(a,t),t.push(`*${this.dynamicArguments?"outputX":e[0]})+`),this.astGeneric(i,t),t.push("]")):(t.push("["),this.astGeneric(a,t),t.push("]"),t.push("["),this.astGeneric(i,t),t.push("]")):void 0!==i&&(t.push("["),this.astGeneric(i,t),t.push("]"))}return t}astCallExpression(e,t){if("CallExpression"!==e.type)throw this.astErrorOutput("Unknown CallExpression",e);let s=this.astMemberExpressionUnroll(e.callee);this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.isAstMathFunction(e),this.onFunctionCall&&this.onFunctionCall(this.name,s,e.arguments),t.push(s),t.push("(");const r=this.lookupFunctionArgumentTypes(s)||[];for(let n=0;n0&&t.push(", "),this.astGeneric(i,t)}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length,n=[];for(let t=0;t{const{utils:s}=i();t.exports={cpuKernelString:function(e,t){const r=[],n=[],i=[],a=!/^function/.test(e.color.toString());if(r.push(" const { context, canvas, constants: incomingConstants } = settings;",` const output = new Int32Array(${JSON.stringify(Array.from(e.output))});`,` const _constantTypes = ${JSON.stringify(e.constantTypes)};`,` const _constants = ${function(e,t){const s=[];for(const r in t){if(!t.hasOwnProperty(r))continue;const n=t[r],i=e[r];switch(n){case"Number":case"Integer":case"Float":case"Boolean":s.push(`${r}:${i}`);break;case"Array(2)":case"Array(3)":case"Array(4)":case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":s.push(`${r}:new ${i.constructor.name}(${JSON.stringify(Array.from(i))})`)}}return`{ ${s.join()} }`}(e.constants,e.constantTypes)};`),n.push(" constants: _constants,"," context,"," output,"," thread: {x: 0, y: 0, z: 0},"),e.graphical){r.push(` const _imageData = context.createImageData(${e.output[0]}, ${e.output[1]});`),r.push(` const _colorData = new Uint8ClampedArray(${e.output[0]} * ${e.output[1]} * 4);`);const t=s.flattenFunctionToString((a?"function ":"")+e.color.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:(e,t)=>null}),o=s.flattenFunctionToString((a?"function ":"")+e.getPixels.toString(),{thisLookup:t=>{switch(t){case"_colorData":return"_colorData";case"_imageData":return"_imageData";case"output":return"output";case"thread":return"this.thread"}return JSON.stringify(e[t])},findDependency:()=>null});n.push(" _imageData,"," _colorData,",` color: ${t},`),i.push(` kernel.getPixels = ${o};`)}const o=[],u=Object.keys(e.constantTypes);for(let t=0;t"this"===t?(a?"function ":"")+e[s].toString():null,thisLookup:e=>{switch(e){case"canvas":return;case"context":return"context"}}});i.push(t),n.push(" _mediaTo2DArray,"),n.push(" _imageTo3DArray,")}else if(-1!==e.argumentTypes.indexOf("HTMLImage")||-1!==o.indexOf("HTMLImage")){const t=s.flattenFunctionToString((a?"function ":"")+e._mediaTo2DArray.toString(),{findDependency:(e,t)=>null,thisLookup:e=>{switch(e){case"canvas":return"settings.canvas";case"context":return"settings.context"}throw new Error("unhandled thisLookup")}});i.push(t),n.push(" _mediaTo2DArray,")}return`function(settings) {\n${r.join("\n")}\n for (const p in _constantTypes) {\n if (!_constantTypes.hasOwnProperty(p)) continue;\n const type = _constantTypes[p];\n switch (type) {\n case 'Number':\n case 'Integer':\n case 'Float':\n case 'Boolean':\n case 'Array(2)':\n case 'Array(3)':\n case 'Array(4)':\n case 'Matrix(2)':\n case 'Matrix(3)':\n case 'Matrix(4)':\n if (incomingConstants.hasOwnProperty(p)) {\n console.warn('constant ' + p + ' of type ' + type + ' cannot be resigned');\n }\n continue;\n }\n if (!incomingConstants.hasOwnProperty(p)) {\n throw new Error('constant ' + p + ' not found');\n }\n _constants[p] = incomingConstants[p];\n }\n const kernel = (function() {\n${e._kernelString}\n })\n .apply({ ${n.join("\n")} });\n ${i.join("\n")}\n return kernel;\n}`}}}),p=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:r}=o(),{CPUFunctionNode:n}=h(),{utils:u}=i(),{cpuKernelString:l}=c();t.exports={CPUKernel:class extends s{static getFeatures(){return this.features}static get features(){return Object.freeze({kernelMap:!0,isIntegerDivisionAccurate:!0})}static get isSupported(){return!0}static isContextMatch(e){return!1}static get mode(){return"cpu"}static nativeFunctionArguments(){return null}static nativeFunctionReturnType(){throw new Error(`Looking up native function return type not supported on ${this.name}`)}static combineKernels(e){return e}static getSignature(e,t){return"cpu"+(t.length>0?":"+t.join(","):"")}constructor(e,t){super(e,t),this.mergeSettings(e.settings||t),this._imageData=null,this._colorData=null,this._kernelString=null,this._prependedString=[],this.thread={x:0,y:0,z:0},this.translatedSources=null}initCanvas(){return"undefined"!=typeof document?document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(0,0):void 0}initContext(){return this.canvas?this.canvas.getContext("2d",{willReadFrequently:!0}):null}initPlugins(e){return[]}validateSettings(e){if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=u.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=u.getDimensions(t);else{if("NumberTexture"!==t&&"ArrayTexture(4)"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=e[0].output}}if(this.graphical&&2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");this.checkOutput()}translateSource(){if(this.leadingReturnStatement=this.output.length>1?"resultX[x] = ":"result[x] = ",this.subKernels){const e=[];for(let t=0;t1?`resultX_${s}[x] = subKernelResult_${s};\n`:`result_${s}[x] = subKernelResult_${s};\n`)}this.followingReturnStatement=e.join("")}const e=r.fromKernel(this,n);this.translatedSources=e.getPrototypes("kernel"),this.graphical||this.returnType||(this.returnType=e.getKernelResultType())}build(){if(this.built)return;if(null!==this.randomSeed&&console.warn("randomSeed is not supported in cpu mode; Math.random() will be unseeded"),this.setupConstants(),this.setupArguments(arguments),this.validateSettings(arguments),this.translateSource(),this.graphical){const{canvas:e,output:t}=this;if(!e)throw new Error("no canvas available for using graphical output");const s=t[0],r=t[1]||1;e.width=s,e.height=r,this._imageData=this.context.createImageData(s,r),this._colorData=new Uint8ClampedArray(s*r*4)}const e=this.getKernelString();this.kernelString=e,this.debug&&(console.log("Function output:"),console.log(e));try{this.run=new Function([],e).bind(this)()}catch(e){console.error("An error occurred compiling the javascript: ",e)}this.buildSignature(arguments),this.built=!0}color(e,t,s,r){void 0===r&&(r=1),e=Math.floor(255*e),t=Math.floor(255*t),s=Math.floor(255*s),r=Math.floor(255*r);const n=this.output[0],i=this.output[1],a=this.thread.x+(i-this.thread.y-1)*n;this._colorData[4*a+0]=e,this._colorData[4*a+1]=t,this._colorData[4*a+2]=s,this._colorData[4*a+3]=r}getKernelString(){if(null!==this._kernelString)return this._kernelString;let e=null,{translatedSources:t}=this;return t.length>1?t=t.filter(t=>/^function/.test(t)?t:(e=t,!1)):e=t.shift(),this._kernelString=` const LOOP_MAX = ${this._getLoopMaxString()};\n ${this.injectedNative||""}\n const _this = this;\n ${this._resultKernelHeader()}\n ${this._processConstants()}\n return (${this.argumentNames.map(e=>"user_"+e).join(", ")}) => {\n ${this._prependedString.join("")}\n ${this._earlyThrows()}\n ${this._processArguments()}\n ${this.graphical?this._graphicalKernelBody(e):this._resultKernelBody(e)}\n ${t.length>0?t.join("\n"):""}\n };`}toString(){return l(this)}_getLoopMaxString(){return this.loopMaxIterations?` ${parseInt(this.loopMaxIterations)};`:" 1000;"}_processConstants(){if(!this.constants)return"";const e=[];for(let t in this.constants)switch(this.constantTypes[t]){case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":e.push(` const constants_${t} = this._mediaTo2DArray(this.constants.${t});\n`);break;case"HTMLImageArray":e.push(` const constants_${t} = this._imageTo3DArray(this.constants.${t});\n`);break;case"Input":e.push(` const constants_${t} = this.constants.${t}.value;\n`);break;default:e.push(` const constants_${t} = this.constants.${t};\n`)}return e.join("")}_earlyThrows(){if(this.graphical)return"";if(this.immutable)return"";if(!this.pipeline)return"";const e=[];for(let t=0;t`user_${r} === result_${e.name}`).join(" || ");t.push(`user_${r} === result${n?` || ${n}`:""}`)}return`if (${t.join(" || ")}) throw new Error('Source and destination arrays are the same. Use immutable = true');`}_processArguments(){const e=[];for(let t=0;t0?e.width:e.videoWidth,r=e.height>0?e.height:e.videoHeight;t.width=0;e--){const t=a[e]=new Array(s);for(let e=0;e`const result_${e.name} = new ${t}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_mutableKernel1DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const result = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const result_${t.name} = new ${e}(outputX);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}`}_resultMutableKernel1DLoop(e){return` const outputX = _this.output[0];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n this.thread.y = 0;\n this.thread.z = 0;\n ${e}\n }`}_resultImmutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_mutableKernel2DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const result = new Array(outputY);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputY);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = result[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = result_${t.name}[y] = new ${e}(outputX);\n`).join("")}\n }`}_resultMutableKernel2DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n const resultX = result[y];\n ${this._mapSubKernels(e=>`const resultX_${e.name} = result_${e.name}[y] = new ${t}(outputX);\n`).join("")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_graphicalKernel2DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n for (let y = 0; y < outputY; y++) {\n this.thread.z = 0;\n this.thread.y = y;\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }`}_resultImmutableKernel3DLoop(e){const t=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y] = new ${t}(outputX);\n ${this._mapSubKernels(e=>`const resultX_${e.name} = resultY_${e.name}[y] = new ${t}(outputX);\n`).join(" ")}\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_mutableKernel3DResults(){const e=this._getKernelResultTypeConstructorString();return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n const result = new Array(outputZ);\n ${this._mapSubKernels(e=>`const result_${e.name} = new Array(outputZ);\n`).join(" ")}\n ${this._mapSubKernels(e=>`let subKernelResult_${e.name};\n`).join(" ")}\n for (let z = 0; z < outputZ; z++) {\n const resultY = result[z] = new Array(outputY);\n ${this._mapSubKernels(e=>`const resultY_${e.name} = result_${e.name}[z] = new Array(outputY);\n`).join(" ")}\n for (let y = 0; y < outputY; y++) {\n const resultX = resultY[y] = new ${e}(outputX);\n ${this._mapSubKernels(t=>`const resultX_${t.name} = resultY_${t.name}[y] = new ${e}(outputX);\n`).join(" ")}\n }\n }`}_resultMutableKernel3DLoop(e){return` const outputX = _this.output[0];\n const outputY = _this.output[1];\n const outputZ = _this.output[2];\n for (let z = 0; z < outputZ; z++) {\n this.thread.z = z;\n const resultY = result[z];\n for (let y = 0; y < outputY; y++) {\n this.thread.y = y;\n const resultX = resultY[y];\n for (let x = 0; x < outputX; x++) {\n this.thread.x = x;\n ${e}\n }\n }\n }`}_kernelOutput(){return this.subKernels?`\n return {\n result: result,\n ${this.subKernels.map(e=>`${e.property}: result_${e.name}`).join(",\n ")}\n };`:"\n return result;"}_mapSubKernels(e){return null===this.subKernels?[""]:this.subKernels.map(e)}destroy(e){e&&delete this.canvas}static destroyContext(e){}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e}setOutput(e){super.setOutput(e);const[t,s]=this.output;this.graphical&&(this._imageData=this.context.createImageData(t,s),this._colorData=new Uint8ClampedArray(t*s*4))}prependString(e){if(this._kernelString)throw new Error("Kernel already built");this._prependedString.push(e)}hasPrependString(e){return this._prependedString.indexOf(e)>-1}}}}),d=e((e,t)=>{t.exports={}}),f=e((e,t)=>{const{Texture:s}=n();function r(e,t){e.activeTexture(e.TEXTURE15),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST)}t.exports={GLTexture:class extends s{get textureType(){throw new Error(`"textureType" not implemented on ${this.name}`)}clone(){return new this.constructor(this)}beforeMutate(){return this.texture._refs>1&&(this.newTexture(),!0)}cloneTexture(){this.texture._refs--;const{context:e,size:t,texture:s,kernel:n}=this;n.debug&&console.warn("cloning internal texture"),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),r(e,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const i=e.createTexture();r(e,i),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,t[0],t[1]),i._refs=1,this.texture=i}newTexture(){this.texture._refs--;const e=this.context,t=this.size;this.kernel.debug&&console.warn("new internal texture");const s=e.createTexture();r(e,s),e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,t[0],t[1],0,this.textureFormat,this.textureType,null),s._refs=1,this.texture=s}clear(){if(this.texture._refs){this.texture._refs--;const e=this.context,t=this.texture=e.createTexture();r(e,t);const s=this.size;t._refs=1,e.texImage2D(e.TEXTURE_2D,0,this.internalFormat,s[0],s[1],0,this.textureFormat,this.textureType,null)}const{context:e,texture:t}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.bindTexture(e.TEXTURE_2D,t),r(e,t),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}delete(){this._deleted||(this._deleted=!0,this.texture._refs&&(this.texture._refs--,this.texture._refs)||(this.kernel&&this.kernel.deleteTexture?this.kernel.deleteTexture(this.texture):this.context.deleteTexture(this.texture)))}framebuffer(){return this._framebuffer||(this._framebuffer=this.kernel.getRawValueFramebuffer(this.size[0],this.size[1])),this._framebuffer}}}}),m=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureFloat:class extends r{get textureType(){return this.context.FLOAT}constructor(e){super(e),this.type="ArrayTexture(1)"}renderRawOutput(){const e=this.context,t=this.size;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const s=new Float32Array(t[0]*t[1]*4);return e.readPixels(0,0,t[0],t[1],e.RGBA,e.FLOAT,s),s}renderValues(){return this._deleted?null:this.renderRawOutput()}toArray(){return s.erectFloat(this.renderValues(),this.output[0])}}}}),g=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erectArray2(this.renderValues(),this.output[0],this.output[1])}}}}),y=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect2DArray2(this.renderValues(),this.output[0],this.output[1])}}}}),x=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray2Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(2)"}toArray(){return s.erect3DArray2(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),b=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erectArray3(this.renderValues(),this.output[0])}}}}),v=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect2DArray3(this.renderValues(),this.output[0],this.output[1])}}}}),S=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray3Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(3)"}toArray(){return s.erect3DArray3(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),T=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erectArray4(this.renderValues(),this.output[0])}}}}),A=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect2DArray4(this.renderValues(),this.output[0],this.output[1])}}}}),w=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureArray4Float3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return s.erect3DArray4(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),_=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat2D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),E=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureFloat3D:class extends r{constructor(e){super(e),this.type="ArrayTexture(1)"}toArray(){return s.erect3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),I=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimizedFloat(this.renderValues(),this.output[0])}}}}),k=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized2D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized2DFloat(this.renderValues(),this.output[0],this.output[1])}}}}),C=e((e,t)=>{const{utils:s}=i(),{GLTextureFloat:r}=m();t.exports={GLTextureMemoryOptimized3D:class extends r{constructor(e){super(e),this.type="MemoryOptimizedNumberTexture"}toArray(){return s.erectMemoryOptimized3DFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),L=e((e,t)=>{const{utils:s}=i(),{GLTexture:r}=f();t.exports={GLTextureUnsigned:class extends r{get textureType(){return this.context.UNSIGNED_BYTE}constructor(e){super(e),this.type="NumberTexture"}renderRawOutput(){const{context:e}=this;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer()),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture,0);const t=new Uint8Array(this.size[0]*this.size[1]*4);return e.readPixels(0,0,this.size[0],this.size[1],e.RGBA,e.UNSIGNED_BYTE,t),t}renderValues(){return this._deleted?null:new Float32Array(this.renderRawOutput().buffer)}toArray(){return s.erectPackedFloat(this.renderValues(),this.output[0])}}}}),D=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned2D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect2DPackedFloat(this.renderValues(),this.output[0],this.output[1])}}}}),F=e((e,t)=>{const{utils:s}=i(),{GLTextureUnsigned:r}=L();t.exports={GLTextureUnsigned3D:class extends r{constructor(e){super(e),this.type="NumberTexture"}toArray(){return s.erect3DPackedFloat(this.renderValues(),this.output[0],this.output[1],this.output[2])}}}}),$=e((e,t)=>{const{GLTextureUnsigned:s}=L();t.exports={GLTextureGraphical:class extends s{constructor(e){super(e),this.type="ArrayTexture(4)"}toArray(){return this.renderValues()}}}}),R=e((e,t)=>{const{Kernel:s}=a(),{utils:r}=i(),{GLTextureArray2Float:n}=g(),{GLTextureArray2Float2D:o}=y(),{GLTextureArray2Float3D:u}=x(),{GLTextureArray3Float:l}=b(),{GLTextureArray3Float2D:h}=v(),{GLTextureArray3Float3D:c}=S(),{GLTextureArray4Float:p}=T(),{GLTextureArray4Float2D:d}=A(),{GLTextureArray4Float3D:f}=w(),{GLTextureFloat:R}=m(),{GLTextureFloat2D:N}=_(),{GLTextureFloat3D:M}=E(),{GLTextureMemoryOptimized:G}=I(),{GLTextureMemoryOptimized2D:O}=k(),{GLTextureMemoryOptimized3D:V}=C(),{GLTextureUnsigned:P}=L(),{GLTextureUnsigned2D:B}=D(),{GLTextureUnsigned3D:z}=F(),{GLTextureGraphical:U}=$();const K={int:"Integer",float:"Number",vec2:"Array(2)",vec3:"Array(3)",vec4:"Array(4)"};t.exports={GLKernel:class extends s{static get mode(){return"gpu"}static getIsFloatRead(){const e=new this("function kernelFunction() {\n return 1;\n }",{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[1],precision:"single",returnType:"Number",tactic:"speed"});e.build(),e.run();const t=e.renderOutput();return e.destroy(!0),1===t[0]}static getIsIntegerDivisionAccurate(){const e=new this(function(e,t){return e[this.thread.x]/t[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[2],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[6,6030401],[3,3991]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),2===s[0]&&1511===s[1]}static getIsSpeedTacticSupported(){const e=new this(function(e){return e[this.thread.x]}.toString(),{context:this.testContext,canvas:this.testCanvas,validate:!1,output:[4],returnType:"Number",precision:"unsigned",tactic:"speed"}),t=[[0,1,2,3]];e.build.apply(e,t),e.run.apply(e,t);const s=e.renderOutput();return e.destroy(!0),0===Math.round(s[0])&&1===Math.round(s[1])&&2===Math.round(s[2])&&3===Math.round(s[3])}static get testCanvas(){throw new Error(`"testCanvas" not defined on ${this.name}`)}static get testContext(){throw new Error(`"testContext" not defined on ${this.name}`)}static getFeatures(){const e=this.testContext,t=this.getIsDrawBuffers();return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),isTextureFloat:this.getIsTextureFloat(),isDrawBuffers:t,kernelMap:t,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static setupFeatureChecks(){throw new Error(`"setupFeatureChecks" not defined on ${this.name}`)}static getSignature(e,t){return e.getVariablePrecisionString()+(t.length>0?":"+t.join(","):"")}setFixIntegerDivisionAccuracy(e){return this.fixIntegerDivisionAccuracy=e,this}setPrecision(e){return this.precision=e,this}setFloatTextures(e){return r.warnDeprecated("method","setFloatTextures","setOptimizeFloatMemory"),this.floatTextures=e,this}static nativeFunctionArguments(e){const t=[],s=[],r=[],n=/^[a-zA-Z_]/,i=/[a-zA-Z_0-9]/;let a=0,o=null,u=null;for(;a0?r[r.length-1]:null;if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"*"!==h)if("MULTI_LINE_COMMENT"!==c||"*"!==l||"/"!==h)if("FUNCTION_ARGUMENTS"!==c||"/"!==l||"/"!==h)if("COMMENT"!==c||"\n"!==l)if(null!==c||"("!==l){if("FUNCTION_ARGUMENTS"===c){if(")"===l){r.pop();break}if("f"===l&&"l"===h&&"o"===e[a+2]&&"a"===e[a+3]&&"t"===e[a+4]&&" "===e[a+5]){r.push("DECLARE_VARIABLE"),u="float",o="",a+=6;continue}if("i"===l&&"n"===h&&"t"===e[a+2]&&" "===e[a+3]){r.push("DECLARE_VARIABLE"),u="int",o="",a+=4;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"2"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec2",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"3"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec3",o="",a+=5;continue}if("v"===l&&"e"===h&&"c"===e[a+2]&&"4"===e[a+3]&&" "===e[a+4]){r.push("DECLARE_VARIABLE"),u="vec4",o="",a+=5;continue}}else if("DECLARE_VARIABLE"===c){if(""===o){if(" "===l){a++;continue}if(!n.test(l))throw new Error("variable name is not expected string")}o+=l,i.test(h)||(r.pop(),s.push(o),t.push(K[u]))}a++}else r.push("FUNCTION_ARGUMENTS"),a++;else r.pop(),a++;else r.push("COMMENT"),a+=2;else r.pop(),a+=2;else r.push("MULTI_LINE_COMMENT"),a+=2}if(r.length>0)throw new Error("GLSL function was not parsable");return{argumentNames:s,argumentTypes:t}}static nativeFunctionReturnType(e){return K[e.match(/int|float|vec[2-4]/)[0]]}static combineKernels(e,t){e.apply(null,arguments);const{texSize:s,context:n,threadDim:i}=t.texSize;let a;if("single"===t.precision){const e=s[0],t=Math.ceil(s[1]/4);a=new Float32Array(e*t*4*4),n.readPixels(0,0,e,4*t,n.RGBA,n.FLOAT,a)}else{const e=new Uint8Array(s[0]*s[1]*4);n.readPixels(0,0,s[0],s[1],n.RGBA,n.UNSIGNED_BYTE,e),a=new Float32Array(e.buffer)}return a=a.subarray(0,i[0]*i[1]*i[2]),1===t.output.length?a:2===t.output.length?r.splitArray(a,t.output[0]):3===t.output.length?r.splitArray(a,t.output[0]*t.output[1]).map(function(e){return r.splitArray(e,t.output[0])}):void 0}constructor(e,t){super(e,t),this.transferValues=null,this.formatValues=null,this.TextureConstructor=null,this.renderOutput=null,this.renderRawOutput=null,this.texSize=null,this.translatedSource=null,this.compiledFragmentShader=null,this.compiledVertexShader=null,this.switchingKernels=null,this._textureSwitched=null,this._mappedTextureSwitched=null}checkTextureSize(){const{features:e}=this.constructor;if(this.texSize[0]>e.maxTextureSize||this.texSize[1]>e.maxTextureSize)throw new Error(`Texture size [${this.texSize[0]},${this.texSize[1]}] generated by kernel is larger than supported size [${e.maxTextureSize},${e.maxTextureSize}]`)}translateSource(){throw new Error(`"translateSource" not defined on ${this.constructor.name}`)}pickRenderStrategy(e){if(this.graphical)return this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=e=>e,this.TextureConstructor=U,null;if("unsigned"===this.precision)if(this.renderRawOutput=this.readPackedPixelsToUint8Array,this.transferValues=this.readPackedPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=z,null):this.output[1]>0?(this.TextureConstructor=B,null):(this.TextureConstructor=P,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else switch(null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.renderOutput=this.renderValues,this.output[2]>0?(this.TextureConstructor=z,this.formatValues=r.erect3DPackedFloat,null):this.output[1]>0?(this.TextureConstructor=B,this.formatValues=r.erect2DPackedFloat,null):(this.TextureConstructor=P,this.formatValues=r.erectPackedFloat,null);case"Array(2)":case"Array(3)":case"Array(4)":return this.requestFallback(e,`${this.returnType} output requires single precision, which this context does not support`)}else{if("single"!==this.precision)throw new Error(`unhandled precision of "${this.precision}"`);if(this.renderRawOutput=this.readFloatPixelsToFloat32Array,this.transferValues=this.readFloatPixelsToFloat32Array,this.pipeline)switch(this.renderOutput=this.renderTexture,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToTextures),this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.optimizeFloatMemory?this.output[2]>0?(this.TextureConstructor=V,null):this.output[1]>0?(this.TextureConstructor=O,null):(this.TextureConstructor=G,null):this.output[2]>0?(this.TextureConstructor=M,null):this.output[1]>0?(this.TextureConstructor=N,null):(this.TextureConstructor=R,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,null):this.output[1]>0?(this.TextureConstructor=o,null):(this.TextureConstructor=n,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,null):this.output[1]>0?(this.TextureConstructor=h,null):(this.TextureConstructor=l,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,null):this.output[1]>0?(this.TextureConstructor=d,null):(this.TextureConstructor=p,null)}if(this.renderOutput=this.renderValues,null!==this.subKernels&&(this.renderKernels=this.renderKernelsToArrays),this.optimizeFloatMemory)switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=V,this.formatValues=r.erectMemoryOptimized3DFloat,null):this.output[1]>0?(this.TextureConstructor=O,this.formatValues=r.erectMemoryOptimized2DFloat,null):(this.TextureConstructor=G,this.formatValues=r.erectMemoryOptimizedFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}else switch(this.returnType){case"LiteralInteger":case"Float":case"Number":case"Integer":return this.output[2]>0?(this.TextureConstructor=M,this.formatValues=r.erect3DFloat,null):this.output[1]>0?(this.TextureConstructor=N,this.formatValues=r.erect2DFloat,null):(this.TextureConstructor=R,this.formatValues=r.erectFloat,null);case"Array(2)":return this.output[2]>0?(this.TextureConstructor=u,this.formatValues=r.erect3DArray2,null):this.output[1]>0?(this.TextureConstructor=o,this.formatValues=r.erect2DArray2,null):(this.TextureConstructor=n,this.formatValues=r.erectArray2,null);case"Array(3)":return this.output[2]>0?(this.TextureConstructor=c,this.formatValues=r.erect3DArray3,null):this.output[1]>0?(this.TextureConstructor=h,this.formatValues=r.erect2DArray3,null):(this.TextureConstructor=l,this.formatValues=r.erectArray3,null);case"Array(4)":return this.output[2]>0?(this.TextureConstructor=f,this.formatValues=r.erect3DArray4,null):this.output[1]>0?(this.TextureConstructor=d,this.formatValues=r.erect2DArray4,null):(this.TextureConstructor=p,this.formatValues=r.erectArray4,null)}}throw new Error(`unhandled return type "${this.returnType}"`)}getKernelString(){throw new Error("abstract method call")}getMainResultTexture(){switch(this.returnType){case"LiteralInteger":case"Float":case"Integer":case"Number":return this.getMainResultNumberTexture();case"Array(2)":return this.getMainResultArray2Texture();case"Array(3)":return this.getMainResultArray3Texture();case"Array(4)":return this.getMainResultArray4Texture();default:throw new Error(`unhandled returnType type ${this.returnType}`)}}getMainResultKernelNumberTexture(){throw new Error("abstract method call")}getMainResultSubKernelNumberTexture(){throw new Error("abstract method call")}getMainResultKernelArray2Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray2Texture(){throw new Error("abstract method call")}getMainResultKernelArray3Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray3Texture(){throw new Error("abstract method call")}getMainResultKernelArray4Texture(){throw new Error("abstract method call")}getMainResultSubKernelArray4Texture(){throw new Error("abstract method call")}getMainResultGraphical(){throw new Error("abstract method call")}getMainResultMemoryOptimizedFloats(){throw new Error("abstract method call")}getMainResultPackedPixels(){throw new Error("abstract method call")}getMainResultString(){return this.graphical?this.getMainResultGraphical():"single"===this.precision?this.optimizeFloatMemory?this.getMainResultMemoryOptimizedFloats():this.getMainResultTexture():this.getMainResultPackedPixels()}getMainResultNumberTexture(){return r.linesToString(this.getMainResultKernelNumberTexture())+r.linesToString(this.getMainResultSubKernelNumberTexture())}getMainResultArray2Texture(){return r.linesToString(this.getMainResultKernelArray2Texture())+r.linesToString(this.getMainResultSubKernelArray2Texture())}getMainResultArray3Texture(){return r.linesToString(this.getMainResultKernelArray3Texture())+r.linesToString(this.getMainResultSubKernelArray3Texture())}getMainResultArray4Texture(){return r.linesToString(this.getMainResultKernelArray4Texture())+r.linesToString(this.getMainResultSubKernelArray4Texture())}getFloatTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} float;\n`}getIntTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic,!0)} int;\n`}getSampler2DTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2D;\n`}getSampler2DArrayTacticDeclaration(){return`precision ${this.getVariablePrecisionString(this.texSize,this.tactic)} sampler2DArray;\n`}renderTexture(){return this.immutable?this.texture.clone():this.texture}readPackedPixelsToUint8Array(){if("unsigned"!==this.precision)throw new Error('Requires this.precision to be "unsigned"');const{texSize:e,context:t}=this,s=new Uint8Array(e[0]*e[1]*4);return t.readPixels(0,0,e[0],e[1],t.RGBA,t.UNSIGNED_BYTE,s),s}readPackedPixelsToFloat32Array(){return new Float32Array(this.readPackedPixelsToUint8Array().buffer)}readFloatPixelsToFloat32Array(){if("single"!==this.precision)throw new Error('Requires this.precision to be "single"');const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r*4);return t.readPixels(0,0,s,r,t.RGBA,t.FLOAT,n),n}getPixels(e){const{context:t,output:s}=this,[n,i]=s,a=new Uint8Array(n*i*4);t.readPixels(0,0,n,i,t.RGBA,t.UNSIGNED_BYTE,a);const o=new Uint8ClampedArray((e?a:r.flipPixels(a,n,i)).buffer);return this.asyncMode?Promise.resolve(o):o}renderKernelsToArrays(){const e={result:this.renderOutput()};for(let t=0;t0){for(let e=0;e0){const{mappedTextures:s}=this;for(let r=0;r{const{utils:s}=i(),{FunctionNode:r}=l(),n={"<":"ceil",">=":"ceil",">":"floor","<=":"floor"};function a(e){if(!e||"object"!=typeof e)return!0;if(Array.isArray(e))return e.every(a);if("UpdateExpression"===e.type||"AssignmentExpression"===e.type||"SequenceExpression"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&!a(e[t]))return!1;return!0}function o(e){let t=!1;function s(e){if(!e||"object"!=typeof e||t)return!1;if(Array.isArray(e))return e.some(s);if("MemberExpression"===e.type&&e.computed)return!0;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1}return function e(r){if(r&&"object"==typeof r&&!t)if(Array.isArray(r))r.forEach(e);else if("MemberExpression"===r.type&&r.computed&&s(r.property))t=!0;else for(const t in r)"loc"!==t&&"range"!==t&&"parent"!==t&&e(r[t])}(e),t}function u(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>u(e,t));if("CallExpression"===e.type&&"Identifier"===e.callee.type&&e.callee.name===t)return!0;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&u(e[s],t))return!0;return!1}function h(e){let t=!1;return function e(s){if(s&&"object"==typeof s&&!t)if(Array.isArray(s))s.forEach(e);else if("CallExpression"===s.type&&"Identifier"===s.callee.type&&s.arguments.some(e=>u(e,s.callee.name)))t=!0;else for(const t in s)"loc"!==t&&"range"!==t&&"parent"!==t&&e(s[t])}(e),t}function c(e){const t="ExpressionStatement"===e.type&&"AssignmentExpression"===e.expression.type?e.expression:null;return function e(s){if(!s||"object"!=typeof s)return!0;if(Array.isArray(s))return s.every(e);if("string"==typeof s.type){if("UpdateExpression"===s.type||"SequenceExpression"===s.type)return!1;if("AssignmentExpression"===s.type&&s!==t)return!1}for(const t in s)if("loc"!==t&&"range"!==t&&"parent"!==t&&!e(s[t]))return!1;return!0}(e)}const p={"Matrix(2)":2,"Matrix(3)":3,"Matrix(4)":4},d={Array:"sampler2D","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4","Matrix(2)":"mat2","Matrix(3)":"mat3","Matrix(4)":"mat4",Array2D:"sampler2D",Array3D:"sampler2D",Boolean:"bool",Float:"float",Input:"sampler2D",Integer:"int",Number:"float",LiteralInteger:"float",NumberTexture:"sampler2D",MemoryOptimizedNumberTexture:"sampler2D","ArrayTexture(1)":"sampler2D","ArrayTexture(2)":"sampler2D","ArrayTexture(3)":"sampler2D","ArrayTexture(4)":"sampler2D",HTMLVideo:"sampler2D",HTMLCanvas:"sampler2D",OffscreenCanvas:"sampler2D",HTMLImage:"sampler2D",ImageBitmap:"sampler2D",ImageData:"sampler2D",HTMLImageArray:"sampler2DArray"},f={"===":"==","!==":"!="};t.exports={WebGLFunctionNode:class extends r{constructor(e,t){super(e,t),t&&t.hasOwnProperty("fixIntegerDivisionAccuracy")&&(this.fixIntegerDivisionAccuracy=t.fixIntegerDivisionAccuracy)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);return null===s&&null===r?(t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t):(t.push("("),this.astGeneric(e.test,t),t.push("?"),this.astGeneric(e.consequent,t),t.push(":"),this.astGeneric(e.alternate,t),t.push(")"),t)}astFunction(e,t){if(this.isRootKernel)t.push("void");else{this.returnType||this.findLastReturn()&&(this.returnType=this.getType(e.body),"LiteralInteger"===this.returnType&&(this.returnType="Number"));const{returnType:s}=this;if(s){const e=d[s];if(!e)throw new Error(`unknown type ${s}`);t.push(e)}else t.push("void")}if(t.push(" "),t.push(this.name),t.push("("),!this.isRootKernel)for(let r=0;r0&&t.push(", ");let i=this.argumentTypes[this.argumentNames.indexOf(n)];if(!i)throw this.astErrorOutput(`Unknown argument ${n} type`,e);"LiteralInteger"===i&&(this.argumentTypes[r]=i="Number");const a=d[i];if(!a)throw this.astErrorOutput("Unexpected expression",e);const o=s.sanitizeName(n);"sampler2D"===a||"sampler2DArray"===a?t.push(`${a} user_${o},ivec2 user_${o}Size,ivec3 user_${o}Dim`):t.push(`${a} user_${o}`)}if(t.push(") {\n"),this.isRootKernel){const e=this.getAssignedArguments();for(let r=0;r>":"bitwiseSignedRightShift",">>>":"bitwiseZeroFillRightShift"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.left)){case"Number":case"Float":this.castValueToInteger(e.left,t);break;case"LiteralInteger":this.castLiteralToInteger(e.left,t);break;default:this.astGeneric(e.left,t)}switch(t.push(","),this.getType(e.right)){case"Number":case"Float":this.castValueToInteger(e.right,t);break;case"LiteralInteger":this.castLiteralToInteger(e.right,t);break;default:this.astGeneric(e.right,t)}return t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){const s={"~":"bitwiseNot"}[e.operator];if(!s)return null;switch(t.push(s),t.push("("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("int("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("float("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("3.402823466e+38");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}markupUserName(e){const t=s.sanitizeName(e);if(this.isRootKernel&&this.getAssignedArguments().has(e)){const s=this.argumentNames.indexOf(e),r=-1===s?null:d[this.argumentTypes[s]];if("float"===r||"int"===r||"bool"===r)return`cellShadow_user_${t}`}return`user_${t}`}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init)if("VariableDeclaration"!==e.init.type)a=!1,this.astGeneric(e.init,s),s.push(";");else{const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e{const t=this.getDeclaration(e);return null!==t&&s.has(t)},a=e=>{if(e&&"object"==typeof e&&!n)if(Array.isArray(e))for(const t of e)a(t);else if("ForStatement"!==e.type||!e.init||"VariableDeclaration"!==e.init.type||!e.init.declarations.some(e=>e.id&&"Identifier"===e.id.type&&r.has(e.id.name)))if("AssignmentExpression"===e.type&&"Identifier"===e.left.type&&i(e.left))n=!0;else if("UpdateExpression"===e.type&&"Identifier"===e.argument.type&&i(e.argument))n=!0;else for(const t in e){if("loc"===t||"range"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&a(s)}};return a(e.body),!n&&e.test&&a(e.test),n}emitForParts(e,t){const{initArr:s,testArr:r,updateArr:n,bodyArr:i,isSafe:a}=e;if(a){const e=s.join(""),a=";"!==e[e.length-1];t.push(`for (${e}${a?";":""}${r.join("")};${n.join("")}){\n`),t.push(i.join("")),t.push("}\n")}else{const e=this.getInternalVariableName("safeI");s.length>0&&t.push(s.join(""),"\n"),t.push(`for (int ${e}=0;${e}0&&t.push(`if (!${r.join("")}) break;\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (int ${s}=0;${s}0){if (!`),this.astGeneric(e.test,t),t.push(") break;}\n"),this.astGeneric(e.body,t),t.push("}\n"),t}astAssignmentExpression(e,t){const s=this.isState("assignment-as-statement");if(s?this.popState("assignment-as-statement"):t.push("("),"%="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("mod("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else if("**="===e.operator)this.astGeneric(e.left,t),t.push("="),t.push("pow("),this.astGeneric(e.left,t),t.push(","),this.astGeneric(e.right,t),t.push(")");else{const s=this.getType(e.left),r=this.getType(e.right);this.astGeneric(e.left,t),t.push(e.operator),"Integer"!==s&&"Integer"===r?(t.push("float("),this.astGeneric(e.right,t),t.push(")")):"Integer"===s&&"LiteralInteger"===r?this.castLiteralToInteger(e.right,t):this.astGeneric(e.right,t)}return s||t.push(")"),t}astBlockStatement(e,t){if(this.isState("loop-body")){this.pushState("block-body");for(let s=0;snull!==e&&(o(e)||h(e))))return null;const i=e=>JSON.parse(JSON.stringify(e)),a=e=>({type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:!0,argument:e},consequent:{type:"BlockStatement",body:[{type:"BreakStatement",label:null}]},alternate:null}),u=e=>"VariableDeclaration"===e.type?e:{type:"ExpressionStatement",expression:e},l="BlockStatement"===e.body.type?e.body.body.slice():[e.body],c=(e,t)=>{const s=e=>{if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);switch(e.type){case"ContinueStatement":return{type:"BlockStatement",body:[...t(),e]};case"ForStatement":case"WhileStatement":case"DoWhileStatement":default:return e;case"IfStatement":return{...e,consequent:s(e.consequent),alternate:s(e.alternate)};case"BlockStatement":return{...e,body:e.body.map(s)};case"SwitchStatement":return{...e,cases:e.cases.map(e=>({...e,consequent:e.consequent.map(s)}))}}};return e.map(s)},p=[];"DoWhileStatement"===t?(p.push(...r?c(l,()=>[a(i(r))]):l),r&&p.push(a(r))):(r&&p.push(a(r)),p.push(...n?c(l,()=>[u(i(n))]):l),n&&p.push(u(n)));const d={type:"BlockStatement",body:[...s?[u(s)]:[],{type:"WhileStatement",test:{type:"Literal",value:!0,raw:"true"},body:{type:"BlockStatement",body:p}}]};return this.stampSyntheticNodes(d),d}stampSyntheticNodes(e){let t=this.syntheticNodeId||1073741824;const s=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(s);else{"string"==typeof e.type&&void 0===e.start&&(e.start=t,e.end=t+1,t+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t])}};s(e),this.syntheticNodeId=t}linearizeStatement(e){const t=[];let s=!1,r=this.linearTempId||0;const n=e=>({type:"Identifier",name:e}),i=(e,t,s)=>({type:"VariableDeclaration",kind:e,declarations:[{type:"VariableDeclarator",id:n(t),init:s}]}),o=(e,t)=>{const s="hoistSeq"+r++;return e.push(i("const",s,t)),n(s)},l=e=>!a(e),h=(e,t)=>{if(s||!e||"object"!=typeof e)return e;switch(e.type){case"Identifier":case"Literal":case"ThisExpression":return e;case"MemberExpression":{const s=h(e.object,t),r=e.computed?h(e.property,t):e.property;return{...e,object:s,property:r}}case"CallExpression":{const s=e.arguments.map(e=>h(e,t));if("Identifier"===e.callee.type)for(let r=0;rh(e,t))};case"UpdateExpression":{if("Identifier"!==e.argument.type)return s=!0,e;if(e.prefix)return t.push({type:"ExpressionStatement",expression:e}),o(t,e.argument);const r=o(t,e.argument);return t.push({type:"ExpressionStatement",expression:e}),r}case"AssignmentExpression":{if("Identifier"!==e.left.type)return s=!0,e;const r=h(e.right,t);return t.push({type:"ExpressionStatement",expression:{...e,right:r}}),o(t,e.left)}case"SequenceExpression":for(let s=0;s({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(e),right:t}});return o.push(d(a,c)),u.push(d(a,p)),t.push({type:"IfStatement",test:s,consequent:{type:"BlockStatement",body:o},alternate:{type:"BlockStatement",body:u}}),n(a)}case"LogicalExpression":{if(!l(e.right))return{...e,left:h(e.left,t)};const s=h(e.left,t),a="hoistSeq"+r++;t.push(i("let",a,s));const o=[],u=h(e.right,o);return o.push({type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:n(a),right:u}}),t.push({type:"IfStatement",test:"&&"===e.operator?n(a):{type:"UnaryExpression",operator:"!",prefix:!0,argument:n(a)},consequent:{type:"BlockStatement",body:o},alternate:null}),n(a)}default:return s=!0,e}};switch(e.type){case"ExpressionStatement":{const s=e.expression;if("AssignmentExpression"===s.type&&"Identifier"===s.left.type){const e=h(s.right,t);t.push({type:"ExpressionStatement",expression:{...s,right:e}})}else{const e=h(s,t);"UpdateExpression"!==e.type&&"AssignmentExpression"!==e.type||t.push({type:"ExpressionStatement",expression:e})}break}case"VariableDeclaration":for(let s=0;s{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(p);else{"string"==typeof e.type&&void 0===e.start&&(e.start=c,e.end=c+1,c+=2);for(const t in e)"loc"!==t&&"range"!==t&&"parent"!==t&&p(e[t])}};return p(t),this.syntheticNodeId=c,t}astStatementWithHoisting(e,t){switch(e.type){case"ExpressionStatement":case"VariableDeclaration":case"ReturnStatement":{if(!c(e))return this.astGeneric(e,t);const s=this.hoistedIndexReads,r=this.hoistedIndexReads=[],n=[];return this.astGeneric(e,n),this.hoistedIndexReads=s,t.push(...r,...n),t}default:return this.astGeneric(e,t)}}astVariableDeclaration(e,t){const r=e.declarations;if(!r||!r[0]||!r[0].init)throw this.astErrorOutput("Unexpected expression",e);const n=[];let i=null;const a=[];let o=[];for(let t=0;t0&&a.push(o.join(",")),n.push(a.join(";")),t.push(n.join("")),t.push(";"),t}astIfStatement(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type||"IfStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}astSwitchCaseConsequent(e,t){const s=[];for(let t=0;t{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;es+1){u=!0,this.astSwitchCaseConsequent(r[s].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[s].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t}astThisExpression(e,t){return t.push("this"),t}astMemberExpression(e,t){const{property:r,name:n,signature:i,origin:a,type:o,xProperty:u,yProperty:l,zProperty:h}=this.getMemberExpressionDetails(e);switch(i){case"value.thread.value":case"this.thread.value":if("x"!==n&&"y"!==n&&"z"!==n)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`threadId.${n}`),t;case"this.output.value":if(this.dynamicOutput)switch(n){case"x":this.isState("casting-to-float")?t.push("float(uOutputDim.x)"):t.push("uOutputDim.x");break;case"y":this.isState("casting-to-float")?t.push("float(uOutputDim.y)"):t.push("uOutputDim.y");break;case"z":this.isState("casting-to-float")?t.push("float(uOutputDim.z)"):t.push("uOutputDim.z");break;default:throw this.astErrorOutput("Unexpected expression",e)}else switch(n){case"x":this.isState("casting-to-integer")?t.push(this.output[0]):t.push(this.output[0],".0");break;case"y":this.isState("casting-to-integer")?t.push(this.output[1]):t.push(this.output[1],".0");break;case"z":this.isState("casting-to-integer")?t.push(this.output[2]):t.push(this.output[2],".0");break;default:throw this.astErrorOutput("Unexpected expression",e)}return t;case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===a)return t.push(Math[n]),t;const i=s.sanitizeName(n);switch(r){case"r":return t.push(`user_${i}.r`),t;case"g":return t.push(`user_${i}.g`),t;case"b":return t.push(`user_${i}.b`),t;case"a":return t.push(`user_${i}.a`),t}break;case"this.constants.value":if(void 0===u)switch(o){case"Array(2)":case"Array(3)":case"Array(4)":return t.push(`constants_${s.sanitizeName(n)}`),t}case"this.constants.value[]":case"this.constants.value[][]":case"this.constants.value[][][]":case"this.constants.value[][][][]":break;case"fn()[]":return this.astCallExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;case"fn()[][]":{const s=e.object.property,r=e.property,n=p[this.getType(e.object.object)],i=e=>"LiteralInteger"===this.getType(e);return!n||i(s)&&i(r)?(this.astCallExpression(e.object.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(s)),t.push("]"),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t):(t.push(`getMatrix${n}(`),this.astCallExpression(e.object.object,t),t.push(", "),t.push(this.memberExpressionPropertyMarkup(s)),t.push(", "),t.push(this.memberExpressionPropertyMarkup(r)),t.push(")"),t)}case"[][]":return this.astArrayExpression(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(r)),t.push("]"),t;default:throw this.astErrorOutput("Unexpected expression",e)}if(!1===e.computed)switch(o){case"Number":case"Integer":case"Float":case"Boolean":return t.push(`${a}_${s.sanitizeName(n)}`),t}const c=`${a}_${s.sanitizeName(n)}`;switch(o){case"Array(2)":case"Array(3)":case"Array(4)":this.astGeneric(e.object,t),t.push("["),t.push(this.memberExpressionPropertyMarkup(u)),t.push("]");break;case"HTMLImageArray":t.push(`getImage3D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(1)":t.push(`getFloatFromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(2)":case"Array2D(2)":case"Array3D(2)":t.push(`getMemoryOptimizedVec2(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(2)":t.push(`getVec2FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(3)":case"Array2D(3)":case"Array3D(3)":t.push(`getMemoryOptimizedVec3(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(3)":t.push(`getVec3FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Array1D(4)":case"Array2D(4)":case"Array3D(4)":t.push(`getMemoryOptimizedVec4(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"ArrayTexture(4)":case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLVideo":t.push(`getVec4FromSampler2D(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"NumberTexture":case"Array":case"Array2D":case"Array3D":case"Array4D":case"Input":case"Number":case"Float":case"Integer":if("single"===this.precision)t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");else{const e="user"===a?this.lookupFunctionArgumentBitRatio(this.name,n):this.constantBitRatios[n];switch(e){case 1:t.push(`get8(${c}, ${c}Size, ${c}Dim, `);break;case 2:t.push(`get16(${c}, ${c}Size, ${c}Dim, `);break;case 4:case 0:t.push(`get32(${c}, ${c}Size, ${c}Dim, `);break;default:throw new Error(`unhandled bit ratio of ${e}`)}this.memberExpressionXYZ(u,l,h,t),t.push(")")}break;case"MemoryOptimizedNumberTexture":t.push(`getMemoryOptimized32(${c}, ${c}Size, ${c}Dim, `),this.memberExpressionXYZ(u,l,h,t),t.push(")");break;case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`${c}[${this.memberExpressionPropertyMarkup(l)}]`),l&&t.push(`[${this.memberExpressionPropertyMarkup(u)}]`);break;default:throw new Error(`unhandled member expression "${o}"`)}return t}astCallExpression(e,t){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);let r=null;const n=this.isAstMathFunction(e);if(r=n||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!r)throw this.astErrorOutput("Unhandled function, couldn't find name",e);switch(r){case"pow":r="_pow";break;case"round":r="_round"}if(this.calledFunctions.indexOf(r)<0&&this.calledFunctions.push(r),"random"===r&&this.plugins&&this.plugins.length>0)for(let e=0;e0&&t.push(", "),"Integer"===n)this.castValueToFloat(r,t);else this.astGeneric(r,t)}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("int("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("float("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){if("Identifier"===a.type)t.push(`user_${s.sanitizeName(a.name)}`);else{if("ArrayExpression"!==a.type&&"MemberExpression"!==a.type&&"CallExpression"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.astGeneric(a,t)}continue}break;case"HTMLCanvas":case"OffscreenCanvas":case"HTMLImage":case"ImageBitmap":case"ImageData":case"HTMLImageArray":case"HTMLVideo":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":case"Array":case"Input":if(o===u){if("Identifier"!==a.type)throw this.astErrorOutput(`Unhandled argument type ${a.type}`,e);this.triggerImplyArgumentBitRatio(this.name,a.name,r,i);const n=s.sanitizeName(a.name);t.push(`user_${n},user_${n}Size,user_${n}Dim`);continue}}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),t}astArrayExpression(e,t){const s=this.getType(e),r=e.elements.length;switch(s){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":t.push(`mat${r}(`);break;default:t.push(`vec${r}(`)}for(let s=0;s0&&t.push(", ");const r=e.elements[s];this.astGeneric(r,t)}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.astGeneric(e,t)}const r=t.join("");if(this.hoistedIndexReads&&/\b\w+\((user_|constants_)\w+, \1\w+Size/.test(r)){const e=`hoisted_${this.hoistedIndexReads.length}_${s.sanitizeName(this.name)}`,t=r.startsWith("int(");return this.hoistedIndexReads.push(`${t?"int":"float"} ${e}=${r};\n`),e}return r}}}}),M=e((e,t)=>{t.exports={name:"math-random-uniformly-distributed",onBeforeRun:e=>{if(null===e.randomSeed||void 0===e.randomSeed)return e.setUniform1f("randomSeed1",Math.random()),void e.setUniform1f("randomSeed2",Math.random());e._mathRandomGenerator&&e._mathRandomGeneratorSeed===e.randomSeed||(e._mathRandomGenerator=function(e){let t=e>>>0;return function(){t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}(e.randomSeed),e._mathRandomGeneratorSeed=e.randomSeed),e.setUniform1f("randomSeed1",e._mathRandomGenerator()),e.setUniform1f("randomSeed2",e._mathRandomGenerator())},functionMatch:"Math.random()",functionReplace:"nrand(vTexCoord)",functionReturnType:"Number",source:"// https://www.shadertoy.com/view/4t2SDh\n//note: uniformly distributed, normalized rand, [0,1]\nhighp float randomSeedShift = 1.0;\nhighp float slide = 1.0;\nuniform highp float randomSeed1;\nuniform highp float randomSeed2;\n\nhighp float nrand(highp vec2 n) {\n highp float result = fract(sin(dot((n.xy + 1.0) * vec2(randomSeed1 * slide, randomSeed2 * randomSeedShift), vec2(12.9898, 78.233))) * 43758.5453);\n randomSeedShift = result;\n if (randomSeedShift > 0.5) {\n slide += 0.00009; \n } else {\n slide += 0.0009;\n }\n return result;\n}"}}),G=e((e,t)=>{t.exports={fragmentShader:`__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nfloat acosh(float x) {\n return log(x + sqrt(x * x - 1.0));\n}\n\nfloat sinh(float x) {\n return (pow(${Math.E}, x) - pow(${Math.E}, -x)) / 2.0;\n}\n\nfloat asinh(float x) {\n return log(x + sqrt(x * x + 1.0));\n}\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat atanh(float x) {\n x = (x + 1.0) / (x - 1.0);\n if (x < 0.0) {\n return 0.5 * log(-x);\n }\n return 0.5 * log(x);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat cosh(float x) {\n return (pow(${Math.E}, x) + pow(${Math.E}, -x)) / 2.0; \n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat tanh(float x) {\n float e = exp(2.0 * x);\n return (e - 1.0) / (e + 1.0);\n}\n\nfloat trunc(float x) {\n if (x >= 0.0) {\n return floor(x); \n } else {\n return ceil(x);\n }\n}\n\nvec4 _round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(_round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(_round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n if (channel == 0) return texel.r * 255.0 + texel.g * 65280.0;\n if (channel == 1) return texel.b * 255.0 + texel.a * 65280.0;\n return 0.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n if (channel == 0) return texel.r * 255.0;\n if (channel == 1) return texel.g * 255.0;\n if (channel == 2) return texel.b * 255.0;\n if (channel == 3) return texel.a * 255.0;\n return 0.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return texel.r;\n if (channel == 1) return texel.g;\n if (channel == 2) return texel.b;\n if (channel == 3) return texel.a;\n return 0.0;\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture2D(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n \n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture2D(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),O=e((e,t)=>{t.exports={vertexShader:"__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),V=e((e,t)=>{function s(e,t={}){const{contextName:s="gl",throwGetError:a,useTrackablePrimitives:o,recording:u=[],variables:l={},onReadPixels:h,onUnrecognizedArgumentLookup:c}=t,p=new Proxy(e,{get:function(t,p){switch(p){case"addComment":return A;case"checkThrowError":return w;case"getReadPixelsVariableName":return m;case"insertVariable":return b;case"reset":return x;case"setIndent":return S;case"toString":return y;case"getContextVariableName":return E}return"function"==typeof e[p]?function(){switch(p){case"getError":return a?u.push(`${g}if (${s}.getError() !== ${s}.NONE) throw new Error('error');`):u.push(`${g}${s}.getError();`),e.getError();case"getExtension":{const t=`${s}Variables${d.length}`;u.push(`${g}const ${t} = ${s}.getExtension('${arguments[0]}');`);const n=e.getExtension(arguments[0]);if(n&&"object"==typeof n){const e=r(n,{getEntity:v,useTrackablePrimitives:o,recording:u,contextName:t,contextVariables:d,variables:l,indent:g,onUnrecognizedArgumentLookup:c});return d.push(e),e}return d.push(null),n}case"readPixels":const t=d.indexOf(arguments[6]);let i;if(-1===t){const e=function(e){if(l)for(const t in l)if(l[t]===e)return t;return null}(arguments[6]);e?(i=e,u.push(`${g}${e}`)):(i=`${s}Variable${d.length}`,d.push(arguments[6]),u.push(`${g}const ${i} = new ${arguments[6].constructor.name}(${arguments[6].length});`))}else i=`${s}Variable${t}`;m=i;const p=[arguments[0],arguments[1],arguments[2],arguments[3],v(arguments[4]),v(arguments[5]),i];return u.push(`${g}${s}.readPixels(${p.join(", ")});`),h&&h(i,p),e.readPixels.apply(e,arguments);case"drawBuffers":return u.push(`${g}${s}.drawBuffers([${n(arguments[0],{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})}]);`),e.drawBuffers(arguments[0])}let t=e[p].apply(e,arguments);switch(typeof t){case"undefined":return void u.push(`${g}${_(p,arguments)};`);case"number":case"boolean":if(o&&-1===d.indexOf(i(t))){u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t=i(t));break}default:null===t?u.push(`${_(p,arguments)};`):u.push(`${g}const ${s}Variable${d.length} = ${_(p,arguments)};`),d.push(t)}return t}:(f[e[p]]=p,e[p])}}),d=[],f={};let m,g="";return p;function y(){return u.join("\n")}function x(){for(;u.length>0;)u.pop()}function b(e,t){l[e]=t}function v(e){const t=f[e];return t?s+"."+t:e}function S(e){g=" ".repeat(e)}function T(e,t){const r=`${s}Variable${d.length}`;return u.push(`${g}const ${r} = ${t};`),d.push(e),r}function A(e){u.push(`${g}// ${e}`)}function w(){u.push(`${g}(() => {\n${g}const error = ${s}.getError();\n${g}if (error !== ${s}.NONE) {\n${g} const names = Object.getOwnPropertyNames(gl);\n${g} for (let i = 0; i < names.length; i++) {\n${g} const name = names[i];\n${g} if (${s}[name] === error) {\n${g} throw new Error('${s} threw ' + name);\n${g} }\n${g} }\n${g}}\n${g}})();`)}function _(e,t){return`${s}.${e}(${n(t,{contextName:s,contextVariables:d,getEntity:v,addVariable:T,variables:l,onUnrecognizedArgumentLookup:c})})`}function E(e){const t=d.indexOf(e);return-1!==t?`${s}Variable${t}`:null}}function r(e,t){const s=new Proxy(e,{get:function(t,s){return"function"==typeof t[s]?function(){if("drawBuffersWEBGL"===s)return h.push(`${p}${a}.drawBuffersWEBGL([${n(arguments[0],{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})}]);`),e.drawBuffersWEBGL(arguments[0]);let t=e[s].apply(e,arguments);switch(typeof t){case"undefined":return void h.push(`${p}${m(s,arguments)};`);case"number":case"boolean":l&&-1===o.indexOf(i(t))?(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t=i(t))):(h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t));break;default:null===t?h.push(`${m(s,arguments)};`):h.push(`${p}const ${a}Variable${o.length} = ${m(s,arguments)};`),o.push(t)}return t}:(r[e[s]]=s,e[s])}}),r={},{contextName:a,contextVariables:o,getEntity:u,useTrackablePrimitives:l,recording:h,variables:c,indent:p,onUnrecognizedArgumentLookup:d}=t;return s;function f(e){return r.hasOwnProperty(e)?`${a}.${r[e]}`:u(e)}function m(e,t){return`${a}.${e}(${n(t,{contextName:a,contextVariables:o,getEntity:f,addVariable:g,variables:c,onUnrecognizedArgumentLookup:d})})`}function g(e,t){const s=`${a}Variable${o.length}`;return o.push(e),h.push(`${p}const ${s} = ${t};`),s}}function n(e,t){const{variables:s,onUnrecognizedArgumentLookup:r}=t;return Array.from(e).map(e=>{const n=function(e){if(s)for(const t in s)if(s.hasOwnProperty(t)&&s[t]===e)return t;return r?r(e):null}(e);return n||function(e,t){const{contextName:s,contextVariables:r,getEntity:n,addVariable:i,onUnrecognizedArgumentLookup:a}=t;if(void 0===e)return"undefined";if(null===e)return"null";const o=r.indexOf(e);if(o>-1)return`${s}Variable${o}`;switch(e.constructor.name){case"String":const t=/\n/.test(e),s=/'/.test(e),r=/"/.test(e);return t?"`"+e+"`":s&&!r?'"'+e+'"':"'"+e+"'";case"Number":case"Boolean":return n(e);case"Array":return i(e,`new ${e.constructor.name}([${Array.from(e).join(",")}])`);case"Float32Array":case"Uint8Array":case"Uint16Array":case"Int32Array":return i(e,`new ${e.constructor.name}(${JSON.stringify(Array.from(e))})`);default:if(a){const t=a(e);if(t)return t}throw new Error(`unrecognized argument type ${e.constructor.name}`)}}(e,t)}).join(", ")}function i(e){return new e.constructor(e)}void 0!==t&&(t.exports={glWiretap:s,glExtensionWiretap:r}),"undefined"!=typeof window&&(s.glExtensionWiretap=r,window.glWiretap=s)}),P=e((e,t)=>{const{glWiretap:s}=V(),{utils:r}=i();function n(e){let t=e.toString().replace(/^function /,"");const s=t.indexOf("=>");if(-1!==s&&!/[{]|\bfunction\b/.test(t.slice(0,s))){const e=t.slice(0,s).trim(),r=t.slice(s+2).trim();t=r.startsWith("{")?`${e} ${r}`:`${e} { return ${r}; }`}return t.replace(/utils[.]/g,"/*utils.*/")}function a(e,t){const s="single"===t.precision?e:`new Float32Array(${e}.buffer)`;return t.output[2]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]}, ${t.output[2]})`:t.output[1]?`renderOutput(${s}, ${t.output[0]}, ${t.output[1]})`:`renderOutput(${s}, ${t.output[0]})`}function o(e,t){const s=e.toArray.toString(),n=!/^function/.test(s);return`() => {\n function framebuffer() { return getReadFramebuffer(); };\n ${r.flattenFunctionToString(`${n?"function ":""}${s}`,{findDependency:(t,s)=>{if("utils"===t)return`const ${s} = ${r[s].toString()};`;if("this"===t)return"framebuffer"===s?"":`${n?"function ":""}${e[s].toString()}`;throw new Error("unhandled fromObject")},thisLookup:(s,r)=>{if("texture"===s)return t;if("context"===s)return r?null:"gl";if(e.hasOwnProperty(s))return JSON.stringify(e[s]);throw new Error(`unhandled thisLookup ${s}`)}})}\n return toArray();\n }`}function u(e,t,s,r,n){if(null===e)return null;if(null===t)return null;switch(typeof e){case"boolean":case"number":return null}if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)for(let n=0;n{switch(typeof e){case"boolean":return new Boolean(e);case"number":return new Number(e);default:return e}}):null;const c=[],p=[],d=s(i.context,{useTrackablePrimitives:!0,onReadPixels:e=>{if(N.subKernels){if(f){const t=N.subKernels[m++].property;p.push(` result${isNaN(t)?"."+t:`[${t}]`} = ${a(e,N)};`)}else p.push(` const result = { result: ${a(e,N)} };`),f=!0;m===N.subKernels.length&&p.push(" return result;")}else e?p.push(` return ${a(e,N)};`):p.push(" return null;")},onUnrecognizedArgumentLookup:e=>{const t=u(e,N.kernelArguments,[],d,c);if(t)return t;const s=u(e,N.kernelConstants,T?Object.keys(T).map(e=>T[e]):[],d,c);return s||null}});let f=!1,m=0;const{source:g,canvas:y,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,kernelArguments:F,kernelConstants:$,tactic:R}=i,N=new e(g,{canvas:y,context:d,checkContext:!1,output:x,pipeline:b,graphical:v,loopMaxIterations:S,constants:T,optimizeFloatMemory:A,precision:w,fixIntegerDivisionAccuracy:_,functions:E,nativeFunctions:I,subKernels:k,immutable:C,argumentTypes:L,constantTypes:D,tactic:R});let M=[];if(d.setIndent(2),N.build.apply(N,t),M.push(d.toString()),d.reset(),N.kernelArguments.forEach((e,s)=>{switch(e.type){case"Integer":case"Boolean":case"Number":case"Float":case"Array":case"Array(2)":case"Array(3)":case"Array(4)":case"HTMLCanvas":case"HTMLImage":case"HTMLVideo":case"Input":d.insertVariable(`uploadValue_${e.name}`,e.uploadValue);break;case"HTMLImageArray":for(let r=0;re.varName).join(", ")}) {`),d.setIndent(4),N.run.apply(N,t),N.renderKernels?N.renderKernels():N.renderOutput&&N.renderOutput(),M.push(" /** start setup uploads for kernel values **/"),N.kernelArguments.forEach(e=>{M.push(" "+e.getStringValueHandler().split("\n").join("\n "))}),M.push(" /** end setup uploads for kernel values **/"),M.push(d.toString()),N.renderOutput===N.renderTexture)if(d.reset(),N.renderKernels){const e=N.renderKernels(),t=d.getContextVariableName(N.texture.texture);M.push(` return {\n result: {\n texture: ${t},\n type: '${e.result.type}',\n toArray: ${o(e.result,t)}\n },`);const{subKernels:s,mappedTextures:r}=N;for(let t=0;t"utils"===e?`const ${t} = ${r[t].toString()};`:null,thisLookup:t=>{if("context"===t)return null;if(e.hasOwnProperty(t))return JSON.stringify(e[t]);throw new Error(`unhandled thisLookup ${t}`)}})}(N)),M.push(" innerKernel.getPixels = getPixels;")),M.push(" return innerKernel;");let G=[];return $.forEach(e=>{G.push(`${e.getStringValueHandler()}`)}),`function kernel(settings) {\n const { context, constants } = settings;\n ${G.join("")}\n ${l||""}\n${M.join("\n")}\n}`}}}),B=e((e,t)=>{t.exports={KernelValue:class{constructor(e,t){const{name:s,kernel:r,context:n,checkContext:i,onRequestContextHandle:a,onUpdateValueMismatch:o,origin:u,strictIntegers:l,type:h,tactic:c}=t;if(!s)throw new Error("name not set");if(!h)throw new Error("type not set");if(!u)throw new Error("origin not set");if("user"!==u&&"constants"!==u)throw new Error(`origin must be "user" or "constants" value is "${u}"`);if(!a)throw new Error("onRequestContextHandle is not set");this.name=s,this.origin=u,this.tactic=c,this.varName="constants"===u?`constants.${s}`:s,this.kernel=r,this.strictIntegers=l,this.type=e.type||h,this.size=e.size||null,this.index=null,this.context=n,this.checkContext=null==i||i,this.contextHandle=null,this.onRequestContextHandle=a,this.onUpdateValueMismatch=o,this.forceUploadEachRun=null}get id(){return`${this.origin}_${name}`}getSource(){throw new Error(`"getSource" not defined on ${this.constructor.name}`)}updateValue(e){throw new Error(`"updateValue" not defined on ${this.constructor.name}`)}}}}),z=e((e,t)=>{const{utils:s}=i(),{KernelValue:r}=B();t.exports={WebGLKernelValue:class extends r{constructor(e,t){super(e,t),this.dimensionsId=null,this.sizeId=null,this.initialValueConstructor=e.constructor,this.onRequestTexture=t.onRequestTexture,this.onRequestIndex=t.onRequestIndex,this.uploadValue=null,this.textureSize=null,this.bitRatio=null,this.prevArg=null}get id(){return`${this.origin}_${s.sanitizeName(this.name)}`}setup(){}rebind(){}getTransferArrayType(e){if(Array.isArray(e[0]))return this.getTransferArrayType(e[0]);switch(e.constructor){case Array:case Int32Array:case Int16Array:case Int8Array:return Float32Array;case Uint8ClampedArray:case Uint8Array:case Uint16Array:case Uint32Array:case Float32Array:case Float64Array:return e.constructor}return console.warn("Unfamiliar constructor type. Will go ahead and use, but likley this may result in a transfer of zeros"),e.constructor}getStringValueHandler(){throw new Error(`"getStringValueHandler" not implemented on ${this.constructor.name}`)}getVariablePrecisionString(){return this.kernel.getVariablePrecisionString(this.textureSize||void 0,this.tactic||void 0)}destroy(){}}}}),U=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueBoolean:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const bool ${this.id} = ${e};\n`:`uniform bool ${this.id};\n`}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),K=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueFloat:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?Number.isInteger(e)?`const float ${this.id} = ${s.glslFloatLiteral(e)};\n`:`const float ${this.id} = ${e};\n`:`uniform float ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1f(this.id,this.uploadValue=e)}}}}),W=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValue:r}=z();t.exports={WebGLKernelValueInteger:class extends r{constructor(e,t){super(e,t),this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(e){return"constants"===this.origin?`const int ${this.id} = ${parseInt(e)};\n`:`uniform int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),j=e((e,t)=>{const{WebGLKernelValue:s}=z(),{Input:n}=r();t.exports={WebGLKernelArray:class extends s{rebind(){if(!this.texture||void 0===this.contextHandle||null===this.contextHandle)return;const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D,this.texture)}checkSize(e,t){if(!this.kernel.validate)return;const{maxTextureSize:s}=this.kernel.constructor.features;if(e>s||t>s)throw e>t?new Error(`Argument texture width of ${e} larger than maximum size of ${s} for your GPU`):e{const{utils:s}=i(),{WebGLKernelArray:r}=j();function n(e){return{width:e.width>0?e.width:e.videoWidth,height:e.height>0?e.height:e.videoHeight}}t.exports={WebGLKernelValueHTMLImage:class extends r{constructor(e,t){super(e,t);const{width:s,height:r}=n(e);this.checkSize(s,r),this.dimensions=[s,r,1],this.textureSize=[s,r],this.uploadValue=e}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue=e),this.kernel.setUniform1i(this.id,this.index)}},mediaSize:n}}),X=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r,mediaSize:n}=q();t.exports={WebGLKernelValueDynamicHTMLImage:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=n(e);this.checkSize(t,s),this.dimensions=[t,s,1],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),H=e((e,t)=>{const{WebGLKernelValueHTMLImage:s}=q();t.exports={WebGLKernelValueHTMLVideo:class extends s{}}}),Y=e((e,t)=>{const{WebGLKernelValueDynamicHTMLImage:s}=X();t.exports={WebGLKernelValueDynamicHTMLVideo:class extends s{}}}),Z=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=4;let[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}.value, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),J=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGLKernelValueDynamicSingleInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Q=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedInput:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e);const[r,n,i]=e.size;this.dimensions=new Int32Array([r||1,n||1,i||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e.value),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}.value, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(value.constructor);const{context:t}=this;s.flattenTo(e.value,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ee=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGLKernelValueDynamicUnsignedInput:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const i=this.getTransferArrayType(e.value);this.preUploadValue=new i(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),te=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),n="Source and destination textures are the same. Use immutable = true and manually cleanup kernel output texture memory with texture.delete()";t.exports={WebGLKernelValueMemoryOptimizedNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r),this.dimensions=e.dimensions,this.textureSize=e.size,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGLKernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),re=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j(),{sameError:n}=te();t.exports={WebGLKernelValueNumberTexture:class extends r{constructor(e,t){super(e,t);const[s,r]=e.size;this.checkSize(s,r);const{size:n,dimensions:i}=e;this.bitRatio=this.getBitRatio(e),this.dimensions=i,this.textureSize=n,this.uploadValue=e.texture,this.forceUploadEachRun=!0}setup(){this.setupTexture()}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName}.texture;\n`}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);if(this.checkContext&&e.context!==this.context)throw new Error(`Value ${this.name} (${this.type}) must be from same context`);const{kernel:t,context:s}=this;if(t.pipeline)if(t.immutable)t.updateTextureArgumentRefs(this,e);else{if(t.texture&&t.texture.texture===e.texture)throw new Error(n);if(t.mappedTextures){const{mappedTextures:s}=t;for(let t=0;t{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGLKernelValueDynamicNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=e.dimensions,this.checkSize(e.size[0],e.size[1]),this.textureSize=e.size,this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ae=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGLKernelValueDynamicSingleArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray1DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],1,1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten2dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGLKernelValueDynamicSingleArray1DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),le=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray2DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],1]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten3dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),he=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGLKernelValueDynamicSingleArray2DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueSingleArray3DI:class extends r{constructor(e,t){super(e,t),this.bitRatio=4,this.setShape(e)}setShape(e){const t=s.getDimensions(e,!0);this.textureSize=s.getMemoryOptimizedFloatTextureSize(t,this.bitRatio),this.dimensions=new Int32Array([t[1],t[2],t[3]]),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength)}getStringValueHandler(){return s.linesToString([`const uploadValue_${this.name} = new Float32Array(${this.uploadArrayLength})`,`flattenTo(${this.varName}, uploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flatten4dArrayTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGLKernelValueDynamicSingleArray3DI:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),de=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray2:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec2 ${this.id} = vec2(${e[0]},${e[1]});\n`:`uniform vec2 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform2fv(this.id,this.uploadValue=e)}}}}),fe=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray3:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec3 ${this.id} = vec3(${e[0]},${e[1]},${e[2]});\n`:`uniform vec3 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform3fv(this.id,this.uploadValue=e)}}}}),me=e((e,t)=>{const{WebGLKernelValue:s}=z();t.exports={WebGLKernelValueArray4:class extends s{constructor(e,t){super(e,t),this.uploadValue=e}getSource(e){return"constants"===this.origin?`const vec4 ${this.id} = vec4(${e[0]},${e[1]},${e[2]},${e[3]});\n`:`uniform vec4 ${this.id};\n`}getStringValueHandler(){return"constants"===this.origin?"":`const uploadValue_${this.name} = ${this.varName};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform4fv(this.id,this.uploadValue=e)}}}}),ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGLKernelValueUnsignedArray:class extends r{constructor(e,t){super(e,t),this.bitRatio=this.getBitRatio(e),this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]),this.TranserArrayType=this.getTransferArrayType(e),this.preUploadValue=new this.TranserArrayType(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer)}getStringValueHandler(){return s.linesToString([`const preUploadValue_${this.name} = new ${this.TranserArrayType.name}(${this.uploadArrayLength})`,`const uploadValue_${this.name} = new Uint8Array(preUploadValue_${this.name}.buffer)`,`flattenTo(${this.varName}, preUploadValue_${this.name})`])}getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.preUploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.UNSIGNED_BYTE,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ye=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGLKernelValueDynamicUnsignedArray:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedPackedTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*(4/this.bitRatio),this.checkSize(this.textureSize[0],this.textureSize[1]);const t=this.getTransferArrayType(e);this.preUploadValue=new t(this.uploadArrayLength),this.uploadValue=new Uint8Array(this.preUploadValue.buffer),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),xe=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U(),{WebGLKernelValueFloat:r}=K(),{WebGLKernelValueInteger:n}=W(),{WebGLKernelValueHTMLImage:i}=q(),{WebGLKernelValueDynamicHTMLImage:a}=X(),{WebGLKernelValueHTMLVideo:o}=H(),{WebGLKernelValueDynamicHTMLVideo:u}=Y(),{WebGLKernelValueSingleInput:l}=Z(),{WebGLKernelValueDynamicSingleInput:h}=J(),{WebGLKernelValueUnsignedInput:c}=Q(),{WebGLKernelValueDynamicUnsignedInput:p}=ee(),{WebGLKernelValueMemoryOptimizedNumberTexture:d}=te(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:f}=se(),{WebGLKernelValueNumberTexture:m}=re(),{WebGLKernelValueDynamicNumberTexture:g}=ne(),{WebGLKernelValueSingleArray:y}=ie(),{WebGLKernelValueDynamicSingleArray:x}=ae(),{WebGLKernelValueSingleArray1DI:b}=oe(),{WebGLKernelValueDynamicSingleArray1DI:v}=ue(),{WebGLKernelValueSingleArray2DI:S}=le(),{WebGLKernelValueDynamicSingleArray2DI:T}=he(),{WebGLKernelValueSingleArray3DI:A}=ce(),{WebGLKernelValueDynamicSingleArray3DI:w}=pe(),{WebGLKernelValueArray2:_}=de(),{WebGLKernelValueArray3:E}=fe(),{WebGLKernelValueArray4:I}=me(),{WebGLKernelValueUnsignedArray:k}=ge(),{WebGLKernelValueDynamicUnsignedArray:C}=ye(),L={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:C,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:p,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:k,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:c,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:x,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":v,"Array1D(3)":v,"Array1D(4)":v,"Array2D(2)":T,"Array2D(3)":T,"Array2D(4)":T,"Array3D(2)":w,"Array3D(3)":w,"Array3D(4)":w,Input:h,NumberTexture:g,"ArrayTexture(1)":g,"ArrayTexture(2)":g,"ArrayTexture(3)":g,"ArrayTexture(4)":g,MemoryOptimizedNumberTexture:f,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:!1,HTMLVideo:u},static:{Boolean:s,Float:r,Integer:n,Array:y,"Array(2)":_,"Array(3)":E,"Array(4)":I,"Array1D(2)":b,"Array1D(3)":b,"Array1D(4)":b,"Array2D(2)":S,"Array2D(3)":S,"Array2D(4)":S,"Array3D(2)":A,"Array3D(3)":A,"Array3D(4)":A,Input:l,NumberTexture:m,"ArrayTexture(1)":m,"ArrayTexture(2)":m,"ArrayTexture(3)":m,"ArrayTexture(4)":m,MemoryOptimizedNumberTexture:d,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:!1,HTMLVideo:o}}};t.exports={lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=L[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]},kernelValueMaps:L}}),be=e((e,t)=>{const{GLKernel:s}=R(),{FunctionBuilder:r}=o(),{WebGLFunctionNode:n}=N(),{utils:a}=i(),u=M(),{fragmentShader:l}=G(),{vertexShader:h}=O(),{glKernelString:c}=P(),{lookupKernelValueType:p}=xe();let d=null,f=null,m=null,g=null,y=null;const x=[u],b=[],v={};t.exports={WebGLKernel:class extends s{static get isSupported(){return null!==d||(this.setupFeatureChecks(),d=this.isContextMatch(m)),d}static setupFeatureChecks(){"undefined"!=typeof document?f=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(f=new OffscreenCanvas(0,0)),f&&(m=f.getContext("webgl"),m||f instanceof OffscreenCanvas||(m=f.getContext("experimental-webgl")),m&&m.getExtension&&(g={OES_texture_float:m.getExtension("OES_texture_float"),OES_texture_float_linear:m.getExtension("OES_texture_float_linear"),OES_element_index_uint:m.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:m.getExtension("WEBGL_draw_buffers")},y=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext}static getIsTextureFloat(){return Boolean(g.OES_texture_float)}static getIsDrawBuffers(){return Boolean(g.WEBGL_draw_buffers)}static getChannelCount(){return g.WEBGL_draw_buffers?m.getParameter(g.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return m.getParameter(m.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return p(e,t,s,r)}static get testCanvas(){return f}static get testContext(){return m}static get features(){return y}static get fragmentShader(){return l}static get vertexShader(){return h}constructor(e,t){super(e,t),this.program=null,this.pipeline=t.pipeline,this.endianness=a.systemEndianness(),this.extensions={},this.argumentTextureCount=0,this.constantTextureCount=0,this.fragShader=null,this.vertShader=null,this.drawBuffersMap=null,this.maxTexSize=null,this.onRequestSwitchKernel=null,this.texture=null,this.mappedTextures=null,this.mergeSettings(e.settings||t),this.threadDim=null,this.framebuffer=null,this.buffer=null,this.textureCache=[],this.programUniformLocationCache={},this.uniform1fCache={},this.uniform1iCache={},this.uniform2fCache={},this.uniform2fvCache={},this.uniform2ivCache={},this.uniform3fvCache={},this.uniform3ivCache={},this.uniform4fvCache={},this.uniform4ivCache={}}initCanvas(){if("undefined"!=typeof document){const e=document.createElement("canvas");return e.width=2,e.height=2,e}if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(0,0)}initContext(){const e={alpha:!1,depth:!1,antialias:!1};return this.canvas.getContext("webgl",e)||this.canvas.getContext("experimental-webgl",e)}initPlugins(e){const t=[],{source:s}=this;if("string"==typeof s)for(let e=0;ee===r.name)&&t.push(r)}return t}initExtensions(){this.extensions={OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:this.context.getExtension("WEBGL_color_buffer_float")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if(!0===this.optimizeFloatMemory&&!t.isTextureFloat)throw new Error("Float textures are not supported");if("single"===this.precision&&!t.isFloatRead)throw new Error("Single precision not supported");if(this.graphical||null!==this.precision||(this.precision=t.isTextureFloat&&t.isFloatRead?"single":"unsigned"),this.subKernels&&this.subKernels.length>0&&!this.extensions.WEBGL_draw_buffers)throw new Error("could not instantiate draw buffers extension");if(null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"precision"===this.precision&&(this.precision="unsigned",console.warn("Cannot use graphical mode and single precision at the same time")),void(this.texSize=a.clone(this.output))}null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}updateMaxTexSize(){const{texSize:e,canvas:t}=this;if(null===this.maxTexSize){let s=b.indexOf(t);-1===s&&(s=b.length,b.push(t),v[s]=[e[0],e[1]]),this.maxTexSize=v[s]}this.maxTexSize[0]this.argumentNames.length)throw new Error("too many arguments for kernel");const{context:s}=this;let r=0;const n=()=>this.createTexture(),i=()=>this.constantTextureCount+r++,o=e=>{this.switchKernels({type:"argumentMismatch",needed:e})},u=()=>s.TEXTURE0+this.constantTextureCount+this.argumentTextureCount++;for(let r=0;rthis.createTexture(),onRequestIndex:()=>r++,onRequestContextHandle:()=>t.TEXTURE0+this.constantTextureCount++});this.constantBitRatios[n]=l.bitRatio,this.kernelConstants.push(l),l.setup(),l.forceUploadEachRun&&this.forceUploadKernelConstants.push(l)}}build(){if(this.built)return;if(this.initExtensions(),this.validateSettings(arguments),this.setupConstants(arguments),this.fallbackRequested)return;if(this.setupArguments(arguments),this.fallbackRequested)return;this.updateMaxTexSize(),this.translateSource();const e=this.pickRenderStrategy(arguments);if(e)return e;const{texSize:t,context:s,canvas:r}=this;s.enable(s.SCISSOR_TEST),this.pipeline&&this.precision,s.viewport(0,0,this.maxTexSize[0],this.maxTexSize[1]),r.width=this.maxTexSize[0],r.height=this.maxTexSize[1];const n=this.threadDim=Array.from(this.output);for(;n.length<3;)n.push(1);const i=this.getVertexShader(arguments),a=s.createShader(s.VERTEX_SHADER);s.shaderSource(a,i),s.compileShader(a),this.vertShader=a;const o=this.getFragmentShader(arguments),u=s.createShader(s.FRAGMENT_SHADER);if(s.shaderSource(u,o),s.compileShader(u),this.fragShader=u,this.debug&&(console.log("GLSL Shader Output:"),console.log(o)),!s.getShaderParameter(a,s.COMPILE_STATUS))throw new Error("Error compiling vertex shader: "+s.getShaderInfoLog(a));if(!s.getShaderParameter(u,s.COMPILE_STATUS))throw new Error("Error compiling fragment shader: "+s.getShaderInfoLog(u));const l=this.program=s.createProgram();s.attachShader(l,a),s.attachShader(l,u),s.linkProgram(l),this.framebuffer=s.createFramebuffer(),this.framebuffer.width=t[0],this.framebuffer.height=t[1],this.rawValueFramebuffers={};const h=new Float32Array([-1,-1,1,-1,-1,1,1,1]),c=new Float32Array([0,0,1,0,0,1,1,1]),p=h.byteLength;let d=this.buffer;d?s.bindBuffer(s.ARRAY_BUFFER,d):(d=this.buffer=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,d),s.bufferData(s.ARRAY_BUFFER,h.byteLength+c.byteLength,s.STATIC_DRAW)),s.bufferSubData(s.ARRAY_BUFFER,0,h),s.bufferSubData(s.ARRAY_BUFFER,p,c);const f=s.getAttribLocation(this.program,"aPos");-1!==f&&(s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0));const m=s.getAttribLocation(this.program,"aTexCoord");-1!==m&&(s.enableVertexAttribArray(m),s.vertexAttribPointer(m,2,s.FLOAT,!1,0,p)),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer);let g=0;s.useProgram(this.program);for(let e in this.constants)this.kernelConstants[g++].updateValue(this.constants[e]);this._setupOutputTexture(),null!==this.subKernels&&this.subKernels.length>0&&(this._mappedTextureSwitched={},this._setupSubOutputTextures()),this.buildSignature(arguments),this.built=!0}translateSource(){const e=r.fromKernel(this,n,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}setupReturnTypes(e){if(this.graphical||this.returnType||(this.returnType=e.getKernelResultType()),this.subKernels&&this.subKernels.length>0)for(let t=0;te.source&&this.source.match(e.functionMatch)?e.source:"").join("\n"):"\n"}_getConstantsString(){const e=[],{threadDim:t,texSize:s}=this;return this.dynamicOutput?e.push("uniform ivec3 uOutputDim","uniform ivec2 uTexSize"):e.push(`ivec3 uOutputDim = ivec3(${t[0]}, ${t[1]}, ${t[2]})`,`ivec2 uTexSize = ivec2(${s[0]}, ${s[1]})`),a.linesToString(e)}_getTextureCoordinate(){const e=this.subKernels;return null===e||e.length<1?"varying vec2 vTexCoord;\n":"out vec2 vTexCoord;\n"}_getDecode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getEncode32EndiannessString(){return"LE"===this.endianness?"":" texel.rgba = texel.abgr;\n"}_getDivideWithIntegerCheckString(){return this.fixIntegerDivisionAccuracy?"float divWithIntCheck(float x, float y) {\n if (floor(x) == x && floor(y) == y) {\n float q = floor(x / y + 0.5);\n if (y * q == x) {\n return q;\n }\n }\n return x / y;\n}\n\nfloat integerCorrectionModulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -(number - (divisor * floor(divWithIntCheck(number, divisor))));\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return number - (divisor * floor(divWithIntCheck(number, divisor)));\n}":""}_getMainArgumentsString(e){const t=[],{argumentNames:s}=this;for(let r=0;r{if(t.hasOwnProperty(s))return t[s];throw`unhandled artifact ${s}`})}getFragmentShader(e){return null!==this.compiledFragmentShader?this.compiledFragmentShader:this.compiledFragmentShader=this.replaceArtifacts(this.constructor.fragmentShader,this._getFragShaderArtifactMap(e))}getVertexShader(e){return null!==this.compiledVertexShader?this.compiledVertexShader:this.compiledVertexShader=this.replaceArtifacts(this.constructor.vertexShader,this._getVertShaderArtifactMap(e))}toString(){const e=a.linesToString(["const gl = context"]);return c(this.constructor,arguments,this,e)}destroy(e){if(!this.context)return;this.buffer&&this.context.deleteBuffer(this.buffer),this.framebuffer&&this.context.deleteFramebuffer(this.framebuffer);for(const e in this.rawValueFramebuffers){for(const t in this.rawValueFramebuffers[e])this.context.deleteFramebuffer(this.rawValueFramebuffers[e][t]),delete this.rawValueFramebuffers[e][t];delete this.rawValueFramebuffers[e]}if(this.vertShader&&this.context.deleteShader(this.vertShader),this.fragShader&&this.context.deleteShader(this.fragShader),this.program&&this.context.deleteProgram(this.program),this.texture){this.texture.delete();const e=this.textureCache.indexOf(this.texture.texture);e>-1&&this.textureCache.splice(e,1),this.texture=null}if(this.mappedTextures&&this.mappedTextures.length){for(let e=0;e-1&&this.textureCache.splice(s,1)}this.mappedTextures=null}if(this.kernelArguments)for(let e=0;e0;){const e=this.textureCache.pop();this.context.deleteTexture(e)}if(e){const e=b.indexOf(this.canvas);e>=0&&(b[e]=null,v[e]=null)}if(this.destroyExtensions(),delete this.context,delete this.canvas,!this.gpu)return;const t=this.gpu.kernels.indexOf(this);-1!==t&&this.gpu.kernels.splice(t,1)}destroyExtensions(){this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("WEBGL_lose_context");t&&t.loseContext()}toJSON(){const e=super.toJSON();return e.functionNodes=r.fromKernel(this,n).toJSON(),e.settings.threadDim=this.threadDim,e}}}}),ve=e((e,t)=>{const s=d(),{WebGLKernel:r}=be(),{glKernelString:n}=P();let i=null,a=null,o=null,u=null,l=null;t.exports={HeadlessGLKernel:class extends r{static get isSupported(){return null!==i||(this.setupFeatureChecks(),i=null!==o),i}static setupFeatureChecks(){if(a=null,u=null,"function"==typeof s)try{if(o=s(2,2,{preserveDrawingBuffer:!0}),!o||!o.getExtension)return;u={STACKGL_resize_drawingbuffer:o.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:o.getExtension("STACKGL_destroy_context"),OES_texture_float:o.getExtension("OES_texture_float"),OES_texture_float_linear:o.getExtension("OES_texture_float_linear"),OES_element_index_uint:o.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:o.getExtension("WEBGL_draw_buffers"),WEBGL_color_buffer_float:o.getExtension("WEBGL_color_buffer_float")},l=this.getFeatures()}catch(e){console.warn(e)}}static isContextMatch(e){try{return"ANGLE"===e.getParameter(e.RENDERER)}catch(e){return!1}}static getIsTextureFloat(){return Boolean(u.OES_texture_float)}static getIsDrawBuffers(){return Boolean(u.WEBGL_draw_buffers)}static getChannelCount(){return u.WEBGL_draw_buffers?o.getParameter(u.WEBGL_draw_buffers.MAX_DRAW_BUFFERS_WEBGL):1}static getMaxTextureSize(){return o.getParameter(o.MAX_TEXTURE_SIZE)}static get testCanvas(){return a}static get testContext(){return o}static get features(){return l}initCanvas(){return{}}initContext(){return s(2,2,{preserveDrawingBuffer:!0})}initExtensions(){this.extensions={STACKGL_resize_drawingbuffer:this.context.getExtension("STACKGL_resize_drawingbuffer"),STACKGL_destroy_context:this.context.getExtension("STACKGL_destroy_context"),OES_texture_float:this.context.getExtension("OES_texture_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear"),OES_element_index_uint:this.context.getExtension("OES_element_index_uint"),WEBGL_draw_buffers:this.context.getExtension("WEBGL_draw_buffers")}}build(){super.build.apply(this,arguments),this.fallbackRequested||this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1])}destroyExtensions(){this.extensions.STACKGL_resize_drawingbuffer=null,this.extensions.STACKGL_destroy_context=null,this.extensions.OES_texture_float=null,this.extensions.OES_texture_float_linear=null,this.extensions.OES_element_index_uint=null,this.extensions.WEBGL_draw_buffers=null}static destroyContext(e){const t=e.getExtension("STACKGL_destroy_context");t&&t.destroy&&t.destroy()}toString(){return n(this.constructor,arguments,this,"const gl = context || require('gl')(1, 1);\n"," if (!context) { gl.getExtension('STACKGL_destroy_context').destroy(); }\n")}setOutput(e){return super.setOutput(e),this.graphical&&this.extensions.STACKGL_resize_drawingbuffer&&this.extensions.STACKGL_resize_drawingbuffer.resize(this.maxTexSize[0],this.maxTexSize[1]),this}}}}),Se=e((e,t)=>{const{utils:s}=i(),{WebGLFunctionNode:r}=N();t.exports={WebGL2FunctionNode:class extends r{astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);if("Infinity"===e.name)t.push("intBitsToFloat(2139095039)");else if("Boolean"===r)if(this.argumentNames.indexOf(n)>-1){const s=this.markupUserName(e.name);t.push(s.startsWith("cellShadow_")?s:`bool(${s})`)}else t.push(`user_${n}`);else t.push(this.markupUserName(e.name));return t}}}}),Te=e((e,t)=>{t.exports={fragmentShader:`#version 300 es\n__HEADER__;\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n__SAMPLER_2D_ARRAY_TACTIC_DECLARATION__;\n\nconst int LOOP_MAX = __LOOP_MAX__;\n\n__PLUGINS__;\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nfloat atan2(float v1, float v2) {\n if (v2 == 0.0) {\n if (v1 == 0.0) return 0.0;\n if (v1 > 0.0) return 1.5707963267948966;\n if (v1 < 0.0) return -1.5707963267948966;\n }\n return atan(v1, v2);\n}\n\nfloat cbrt(float x) {\n if (x >= 0.0) {\n return pow(x, 1.0 / 3.0);\n } else {\n return -pow(x, 1.0 / 3.0);\n }\n}\n\nfloat expm1(float x) {\n return pow(${Math.E}, x) - 1.0; \n}\n\nfloat fround(highp float x) {\n return x;\n}\n\nfloat imul(float v1, float v2) {\n return float(int(v1) * int(v2));\n}\n\nfloat log10(float x) {\n return log2(x) * (1.0 / log2(10.0));\n}\n\nfloat log1p(float x) {\n return log(1.0 + x);\n}\n\nfloat _pow(float v1, float v2) {\n if (v2 == 0.0) return 1.0;\n return pow(v1, v2);\n}\n\nfloat _round(float x) {\n return floor(x + 0.5);\n}\n\n\nconst int BIT_COUNT = 32;\nint modi(int x, int y) {\n return x - y * (x / y);\n}\n\nint bitwiseOr(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) || (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseXOR(int a, int b) {\n int result = 0;\n int n = 1;\n \n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) != (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 || b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseAnd(int a, int b) {\n int result = 0;\n int n = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if ((modi(a, 2) == 1) && (modi(b, 2) == 1)) {\n result += n;\n }\n a = a / 2;\n b = b / 2;\n n = n * 2;\n if(!(a > 0 && b > 0)) {\n break;\n }\n }\n return result;\n}\nint bitwiseNot(int a) {\n // ~a is identically -a - 1 in two's complement, for every value including\n // negatives. The previous bit-by-bit loop only worked for a >= 0, where it\n // leaned on 32-bit overflow wrapping to reach the negative answer; given a\n // negative input it computed ~abs(a), so ~(-1) gave -2 and ~~x never\n // returned x.\n return -a - 1;\n}\nint bitwiseZeroFillLeftShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n *= 2;\n }\n\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\n// _pow2 is defined further down, alongside encode32/decode32\nfloat _pow2(float e);\nint bitwiseSignedRightShift(int num, int shifts) {\n // pow(2.0, n) is approximate on many GPUs, and landing 1 ulp high makes the\n // division fall just under a whole number, which floor() then rounds away:\n // 2 >> 1 came out 0, 8 >> 1 came out 3. Only exact left operands were\n // affected, odd ones having enough slack to survive. _pow2 is exact.\n return int(floor(float(num) / _pow2(float(shifts))));\n}\n\nint bitwiseZeroFillRightShift(int n, int shift) {\n int maxBytes = BIT_COUNT;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (maxBytes >= n) {\n break;\n }\n maxBytes *= 2;\n }\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= shift) {\n break;\n }\n n /= 2;\n }\n int result = 0;\n int byteVal = 1;\n for (int i = 0; i < BIT_COUNT; i++) {\n if (i >= maxBytes) break;\n if (modi(n, 2) > 0) { result += byteVal; }\n n = int(n / 2);\n byteVal *= 2;\n }\n return result;\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n// GLSL ES 1.00 accepts only a constant or a loop symbol inside an index\n// expression, so m[y][x] does not compile when y and x come from kernel\n// arguments -- the error is "Index expression can only contain const or loop\n// symbols". Loop counters are legal indices, so walk the matrix with them\n// instead. These are 2x2 to 4x4, so it costs at most sixteen comparisons.\nfloat getMatrix2(mat2 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix3(mat3 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\nfloat getMatrix4(mat4 m, int y, int x) {\n float result = 0.0;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if (i == y && j == x) result = m[i][j];\n }\n }\n return result;\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\n// Exact powers of two built from exact constant multiplies: exp2/log2/pow\n// are approximate on some GPUs (notably Apple silicon), and 1-2 ulp there\n// corrupts the packed bytes (#659)\nfloat _pow2(float e) {\n float r = 1.0;\n float a = abs(e);\n bool n = e < 0.0;\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 64.0) { r *= n ? 5.421010862427522e-20 : 18446744073709551616.0; a -= 64.0; }\n if (a >= 32.0) { r *= n ? 2.3283064365386963e-10 : 4294967296.0; a -= 32.0; }\n if (a >= 16.0) { r *= n ? 0.0000152587890625 : 65536.0; a -= 16.0; }\n if (a >= 8.0) { r *= n ? 0.00390625 : 256.0; a -= 8.0; }\n if (a >= 4.0) { r *= n ? 0.0625 : 16.0; a -= 4.0; }\n if (a >= 2.0) { r *= n ? 0.25 : 4.0; a -= 2.0; }\n if (a >= 1.0) { r *= n ? 0.5 : 2.0; }\n return r;\n}\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 texel) {\n __DECODE32_ENDIANNESS__;\n texel *= 255.0;\n vec2 gte128;\n gte128.x = texel.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = texel.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * texel.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = _pow2(round(exponent));\n texel.b = texel.b - 128.0 * gte128.x;\n res = dot(texel, SCALE_FACTOR) * _pow2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nfloat decode16(vec4 texel, int index) {\n int channel = integerMod(index, 2);\n return texel[channel*2] * 255.0 + texel[channel*2 + 1] * 65280.0;\n}\n\nfloat decode8(vec4 texel, int index) {\n int channel = integerMod(index, 4);\n return texel[channel] * 255.0;\n}\n\nvec4 legacyEncode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 texel = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n texel.rg = integerMod(texel.rg, 256.0);\n texel.b = integerMod(texel.b, 128.0);\n texel.a = exponent*0.5 + 63.5;\n texel.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n texel = floor(texel);\n texel *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return texel;\n}\n\n// https://github.com/gpujs/gpu.js/wiki/Encoder-details\nvec4 encode32(float value) {\n if (value == 0.0) return vec4(0, 0, 0, 0);\n\n float exponent;\n float mantissa;\n vec4 result;\n float sgn;\n\n sgn = step(0.0, -value);\n value = abs(value);\n\n exponent = floor(log2(value));\n float p2 = _pow2(exponent);\n // approximate log2 can land one off; correct by direct comparison\n if (p2 > value) { exponent -= 1.0; p2 *= 0.5; }\n else if (p2 * 2.0 <= value) { exponent += 1.0; p2 *= 2.0; }\n\n mantissa = value / p2 - 1.0;\n exponent = exponent+127.0;\n result = vec4(0,0,0,0);\n\n result.a = floor(exponent/2.0);\n exponent = exponent - result.a*2.0;\n result.a = result.a + 128.0*sgn;\n\n result.b = floor(mantissa * 128.0);\n mantissa = mantissa - result.b / 128.0;\n result.b = result.b + exponent*128.0;\n\n result.g = floor(mantissa*32768.0);\n mantissa = mantissa - result.g/32768.0;\n\n result.r = floor(mantissa*8388608.0);\n return result/255.0;\n}\n// Dragons end here\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return decode32(texel);\n}\n\nfloat get16(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 2;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 2, texSize.y));\n return decode16(texel, index);\n}\n\nfloat get8(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int w = texSize.x * 4;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize.x * 4, texSize.y));\n return decode8(texel, index);\n}\n\nfloat getMemoryOptimized32(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + (texDim.x * (y + (texDim.y * z)));\n int channel = integerMod(index, 4);\n index = index / 4;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n index = index / 4;\n vec4 texel = texture(tex, st / vec2(texSize));\n return texel[channel];\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat getFloatFromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return result[0];\n}\n\nvec2 getVec2FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec2(result[0], result[1]);\n}\n\nvec2 getMemoryOptimizedVec2(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n index = index / 2;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n if (channel == 0) return vec2(texel.r, texel.g);\n if (channel == 1) return vec2(texel.b, texel.a);\n return vec2(0.0, 0.0);\n}\n\nvec3 getVec3FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n vec4 result = getImage2D(tex, texSize, texDim, z, y, x);\n return vec3(result[0], result[1], result[2]);\n}\n\nvec3 getMemoryOptimizedVec3(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int fieldIndex = 3 * (x + texDim.x * (y + texDim.y * z));\n int vectorIndex = fieldIndex / 4;\n int vectorOffset = fieldIndex - vectorIndex * 4;\n int readY = vectorIndex / texSize.x;\n int readX = vectorIndex - readY * texSize.x;\n vec4 tex1 = texture(tex, (vec2(readX, readY) + 0.5) / vec2(texSize));\n\n if (vectorOffset == 0) {\n return tex1.xyz;\n } else if (vectorOffset == 1) {\n return tex1.yzw;\n } else {\n readX++;\n if (readX >= texSize.x) {\n readX = 0;\n readY++;\n }\n vec4 tex2 = texture(tex, vec2(readX, readY) / vec2(texSize));\n if (vectorOffset == 2) {\n return vec3(tex1.z, tex1.w, tex2.x);\n } else {\n return vec3(tex1.w, tex2.x, tex2.y);\n }\n }\n}\n\nvec4 getVec4FromSampler2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n return getImage2D(tex, texSize, texDim, z, y, x);\n}\n\nvec4 getMemoryOptimizedVec4(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n int index = x + texDim.x * (y + texDim.y * z);\n int channel = integerMod(index, 2);\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n vec4 texel = texture(tex, st / vec2(texSize));\n return vec4(texel.r, texel.g, texel.b, texel.a);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nfloat modulo(float number, float divisor) {\n if (number < 0.0) {\n number = abs(number);\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return -mod(number, divisor);\n }\n if (divisor < 0.0) {\n divisor = abs(divisor);\n }\n return mod(number, divisor);\n}\n\n__INJECTED_NATIVE__;\n__MAIN_CONSTANTS__;\n__MAIN_ARGUMENTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}`}}),Ae=e((e,t)=>{t.exports={vertexShader:"#version 300 es\n__FLOAT_TACTIC_DECLARATION__;\n__INT_TACTIC_DECLARATION__;\n__SAMPLER_2D_TACTIC_DECLARATION__;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"}}),we=e((e,t)=>{const{WebGLKernelValueBoolean:s}=U();t.exports={WebGL2KernelValueBoolean:class extends s{}}}),_e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueFloat:r}=K();t.exports={WebGL2KernelValueFloat:class extends r{}}}),Ee=e((e,t)=>{const{WebGLKernelValueInteger:s}=W();t.exports={WebGL2KernelValueInteger:class extends s{getSource(e){const t=this.getVariablePrecisionString();return"constants"===this.origin?`const ${t} int ${this.id} = ${parseInt(e)};\n`:`uniform ${t} int ${this.id};\n`}updateValue(e){"constants"!==this.origin&&this.kernel.setUniform1i(this.id,this.uploadValue=e)}}}}),Ie=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueHTMLImage:r}=q();t.exports={WebGL2KernelValueHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),ke=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicHTMLImage:r}=X();t.exports={WebGL2KernelValueDynamicHTMLImage:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ce=e((e,t)=>{const{utils:s}=i(),{WebGLKernelArray:r}=j();t.exports={WebGL2KernelValueHTMLImageArray:class extends r{constructor(e,t){super(e,t),this.checkSize(e[0].width,e[0].height),this.dimensions=[e[0].width,e[0].height,e.length],this.textureSize=[e[0].width,e[0].height]}defineTexture(){const{context:e}=this;e.activeTexture(this.contextHandle),e.bindTexture(e.TEXTURE_2D_ARRAY,this.texture),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D_ARRAY,e.TEXTURE_MIN_FILTER,e.NEAREST)}getStringValueHandler(){return`const uploadValue_${this.name} = ${this.varName};\n`}getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D_ARRAY,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!0),t.texImage3D(t.TEXTURE_2D_ARRAY,0,t.RGBA,e[0].width,e[0].height,e.length,0,t.RGBA,t.UNSIGNED_BYTE,null);for(let s=0;s{const{utils:s}=i(),{WebGL2KernelValueHTMLImageArray:r}=Ce();t.exports={WebGL2KernelValueDynamicHTMLImageArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2DArray ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){const{width:t,height:s}=e[0];this.checkSize(t,s),this.dimensions=[t,s,e.length],this.textureSize=[t,s],this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),De=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueHTMLImage:r}=Ie();t.exports={WebGL2KernelValueHTMLVideo:class extends r{}}}),Fe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueDynamicHTMLImage:r}=ke();t.exports={WebGL2KernelValueDynamicHTMLVideo:class extends r{}}}),$e=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleInput:r}=Z();t.exports={WebGL2KernelValueSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){const{context:t}=this;s.flattenTo(e.value,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Re=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleInput:r}=$e();t.exports={WebGL2KernelValueDynamicSingleInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){let[t,r,n]=e.size;this.dimensions=new Int32Array([t||1,r||1,n||1]),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ne=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedInput:r}=Q();t.exports={WebGL2KernelValueUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Me=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedInput:r}=ee();t.exports={WebGL2KernelValueDynamicUnsignedInput:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Ge=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueMemoryOptimizedNumberTexture:r}=te();t.exports={WebGL2KernelValueMemoryOptimizedNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Oe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicMemoryOptimizedNumberTexture:r}=se();t.exports={WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:class extends r{getSource(){return s.linesToString([`uniform sampler2D ${this.id}`,`uniform ivec2 ${this.sizeId}`,`uniform ivec3 ${this.dimensionsId}`])}}}}),Ve=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueNumberTexture:r}=re();t.exports={WebGL2KernelValueNumberTexture:class extends r{getSource(){const{id:e,sizeId:t,textureSize:r,dimensionsId:n,dimensions:i}=this,a=this.getVariablePrecisionString();return s.linesToString([`uniform ${a} sampler2D ${e}`,`${a} ivec2 ${t} = ivec2(${r[0]}, ${r[1]})`,`${a} ivec3 ${n} = ivec3(${i[0]}, ${i[1]}, ${i[2]})`])}}}}),Pe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicNumberTexture:r}=ne();t.exports={WebGL2KernelValueDynamicNumberTexture:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),Be=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray:r}=ie();t.exports={WebGL2KernelValueSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}updateValue(e){if(!s.isArray(e))return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),ze=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray:r}=Be();t.exports={WebGL2KernelValueDynamicSingleArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.dimensions=s.getDimensions(e,!0),this.textureSize=s.getMemoryOptimizedFloatTextureSize(this.dimensions,this.bitRatio),this.uploadArrayLength=this.textureSize[0]*this.textureSize[1]*this.bitRatio,this.checkSize(this.textureSize[0],this.textureSize[1]),this.uploadValue=new Float32Array(this.uploadArrayLength),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),Ue=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray1DI:r}=oe();t.exports={WebGL2KernelValueSingleArray1DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Ke=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray1DI:r}=Ue();t.exports={WebGL2KernelValueDynamicSingleArray1DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),We=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray2DI:r}=le();t.exports={WebGL2KernelValueSingleArray2DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),je=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray2DI:r}=We();t.exports={WebGL2KernelValueDynamicSingleArray2DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueSingleArray3DI:r}=ce();t.exports={WebGL2KernelValueSingleArray3DI:class extends r{updateValue(e){if(e.constructor!==this.initialValueConstructor)return void this.onUpdateValueMismatch(e.constructor);const{context:t}=this;s.flattenTo(e,this.uploadValue),t.activeTexture(this.contextHandle),t.bindTexture(t.TEXTURE_2D,this.texture),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,this.textureSize[0],this.textureSize[1],0,t.RGBA,t.FLOAT,this.uploadValue),this.kernel.setUniform1i(this.id,this.index)}}}}),Xe=e((e,t)=>{const{utils:s}=i(),{WebGL2KernelValueSingleArray3DI:r}=qe();t.exports={WebGL2KernelValueDynamicSingleArray3DI:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}updateValue(e){this.setShape(e),this.kernel.setUniform3iv(this.dimensionsId,this.dimensions),this.kernel.setUniform2iv(this.sizeId,this.textureSize),super.updateValue(e)}}}}),He=e((e,t)=>{const{WebGLKernelValueArray2:s}=de();t.exports={WebGL2KernelValueArray2:class extends s{}}}),Ye=e((e,t)=>{const{WebGLKernelValueArray3:s}=fe();t.exports={WebGL2KernelValueArray3:class extends s{}}}),Ze=e((e,t)=>{const{WebGLKernelValueArray4:s}=me();t.exports={WebGL2KernelValueArray4:class extends s{}}}),Je=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueUnsignedArray:r}=ge();t.exports={WebGL2KernelValueUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`${e} ivec2 ${this.sizeId} = ivec2(${this.textureSize[0]}, ${this.textureSize[1]})`,`${e} ivec3 ${this.dimensionsId} = ivec3(${this.dimensions[0]}, ${this.dimensions[1]}, ${this.dimensions[2]})`])}}}}),Qe=e((e,t)=>{const{utils:s}=i(),{WebGLKernelValueDynamicUnsignedArray:r}=ye();t.exports={WebGL2KernelValueDynamicUnsignedArray:class extends r{getSource(){const e=this.getVariablePrecisionString();return s.linesToString([`uniform ${e} sampler2D ${this.id}`,`uniform ${e} ivec2 ${this.sizeId}`,`uniform ${e} ivec3 ${this.dimensionsId}`])}}}}),et=e((e,t)=>{const{WebGL2KernelValueBoolean:s}=we(),{WebGL2KernelValueFloat:r}=_e(),{WebGL2KernelValueInteger:n}=Ee(),{WebGL2KernelValueHTMLImage:i}=Ie(),{WebGL2KernelValueDynamicHTMLImage:a}=ke(),{WebGL2KernelValueHTMLImageArray:o}=Ce(),{WebGL2KernelValueDynamicHTMLImageArray:u}=Le(),{WebGL2KernelValueHTMLVideo:l}=De(),{WebGL2KernelValueDynamicHTMLVideo:h}=Fe(),{WebGL2KernelValueSingleInput:c}=$e(),{WebGL2KernelValueDynamicSingleInput:p}=Re(),{WebGL2KernelValueUnsignedInput:d}=Ne(),{WebGL2KernelValueDynamicUnsignedInput:f}=Me(),{WebGL2KernelValueMemoryOptimizedNumberTexture:m}=Ge(),{WebGL2KernelValueDynamicMemoryOptimizedNumberTexture:g}=Oe(),{WebGL2KernelValueNumberTexture:y}=Ve(),{WebGL2KernelValueDynamicNumberTexture:x}=Pe(),{WebGL2KernelValueSingleArray:b}=Be(),{WebGL2KernelValueDynamicSingleArray:v}=ze(),{WebGL2KernelValueSingleArray1DI:S}=Ue(),{WebGL2KernelValueDynamicSingleArray1DI:T}=Ke(),{WebGL2KernelValueSingleArray2DI:A}=We(),{WebGL2KernelValueDynamicSingleArray2DI:w}=je(),{WebGL2KernelValueSingleArray3DI:_}=qe(),{WebGL2KernelValueDynamicSingleArray3DI:E}=Xe(),{WebGL2KernelValueArray2:I}=He(),{WebGL2KernelValueArray3:k}=Ye(),{WebGL2KernelValueArray4:C}=Ze(),{WebGL2KernelValueUnsignedArray:L}=Je(),{WebGL2KernelValueDynamicUnsignedArray:D}=Qe(),F={unsigned:{dynamic:{Boolean:s,Integer:n,Float:r,Array:D,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:f,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:L,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":!1,"Array1D(3)":!1,"Array1D(4)":!1,"Array2D(2)":!1,"Array2D(3)":!1,"Array2D(4)":!1,"Array3D(2)":!1,"Array3D(3)":!1,"Array3D(4)":!1,Input:d,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:g,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}},single:{dynamic:{Boolean:s,Integer:n,Float:r,Array:v,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":T,"Array1D(3)":T,"Array1D(4)":T,"Array2D(2)":w,"Array2D(3)":w,"Array2D(4)":w,"Array3D(2)":E,"Array3D(3)":E,"Array3D(4)":E,Input:p,NumberTexture:x,"ArrayTexture(1)":x,"ArrayTexture(2)":x,"ArrayTexture(3)":x,"ArrayTexture(4)":x,MemoryOptimizedNumberTexture:g,HTMLCanvas:a,OffscreenCanvas:a,HTMLImage:a,ImageBitmap:a,ImageData:a,HTMLImageArray:u,HTMLVideo:h},static:{Boolean:s,Float:r,Integer:n,Array:b,"Array(2)":I,"Array(3)":k,"Array(4)":C,"Array1D(2)":S,"Array1D(3)":S,"Array1D(4)":S,"Array2D(2)":A,"Array2D(3)":A,"Array2D(4)":A,"Array3D(2)":_,"Array3D(3)":_,"Array3D(4)":_,Input:c,NumberTexture:y,"ArrayTexture(1)":y,"ArrayTexture(2)":y,"ArrayTexture(3)":y,"ArrayTexture(4)":y,MemoryOptimizedNumberTexture:m,HTMLCanvas:i,OffscreenCanvas:i,HTMLImage:i,ImageBitmap:i,ImageData:i,HTMLImageArray:o,HTMLVideo:l}}};t.exports={kernelValueMaps:F,lookupKernelValueType:function(e,t,s,r){if(!e)throw new Error("type missing");if(!t)throw new Error("dynamic missing");if(!s)throw new Error("precision missing");r.type&&(e=r.type);const n=F[s][t];if("WebGPUBuffer"===e)throw new Error("this kernel runs on WebGL but received a WebGPU pipeline buffer; await handle.toArray() first, or give this kernel the async contract (asyncMode: true / mode: 'async') so the readback happens for you");if(!1===n[e])return null;if(void 0===n[e])throw new Error(`Could not find a KernelValue for ${e}`);return n[e]}}}),tt=e((e,t)=>{const{WebGLKernel:s}=be(),{WebGL2FunctionNode:r}=Se(),{FunctionBuilder:n}=o(),{utils:a}=i(),{fragmentShader:u}=Te(),{vertexShader:l}=Ae(),{lookupKernelValueType:h}=et();let c=null,p=null,d=null,f=null;t.exports={WebGL2Kernel:class extends s{static get isSupported(){return null!==c||(this.setupFeatureChecks(),c=this.isContextMatch(d)),c}static setupFeatureChecks(){"undefined"!=typeof document?p=document.createElement("canvas"):"undefined"!=typeof OffscreenCanvas&&(p=new OffscreenCanvas(0,0)),p&&(d=p.getContext("webgl2"),d&&d.getExtension&&(d.getExtension("EXT_color_buffer_float"),d.getExtension("OES_texture_float_linear"),f=this.getFeatures()))}static isContextMatch(e){return"undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext}static getFeatures(){const e=this.testContext;return Object.freeze({isFloatRead:this.getIsFloatRead(),isIntegerDivisionAccurate:this.getIsIntegerDivisionAccurate(),isSpeedTacticSupported:this.getIsSpeedTacticSupported(),kernelMap:!0,isTextureFloat:!0,isDrawBuffers:!0,channelCount:this.getChannelCount(),maxTextureSize:this.getMaxTextureSize(),lowIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_INT),lowFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.LOW_FLOAT),mediumIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_INT),mediumFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),highIntPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_INT),highFloatPrecision:e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT)})}static getIsTextureFloat(){return!0}static getChannelCount(){return d.getParameter(d.MAX_DRAW_BUFFERS)}static getMaxTextureSize(){return d.getParameter(d.MAX_TEXTURE_SIZE)}static lookupKernelValueType(e,t,s,r){return h(e,t,s,r)}static get testCanvas(){return p}static get testContext(){return d}static get features(){return f}static get fragmentShader(){return u}static get vertexShader(){return l}initContext(){return this.canvas.getContext("webgl2",{alpha:!1,depth:!1,antialias:!1})}initExtensions(){this.extensions={EXT_color_buffer_float:this.context.getExtension("EXT_color_buffer_float"),OES_texture_float_linear:this.context.getExtension("OES_texture_float_linear")}}validateSettings(e){if(!this.validate)return void(this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output));const{features:t}=this.constructor;if("single"===this.precision&&!t.isFloatRead)throw new Error("Float texture outputs are not supported");if(this.graphical||null!==this.precision||(this.precision=t.isFloatRead?"single":"unsigned"),null===this.fixIntegerDivisionAccuracy?this.fixIntegerDivisionAccuracy=!t.isIntegerDivisionAccurate:this.fixIntegerDivisionAccuracy&&t.isIntegerDivisionAccurate&&(this.fixIntegerDivisionAccuracy=!1),this.checkOutput(),!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=a.getVariableType(e[0],this.strictIntegers);switch(t){case"Array":this.output=a.getDimensions(t);break;case"NumberTexture":case"MemoryOptimizedNumberTexture":case"ArrayTexture(1)":case"ArrayTexture(2)":case"ArrayTexture(3)":case"ArrayTexture(4)":this.output=e[0].output;break;default:throw new Error("Auto output not supported for input type: "+t)}}if(this.graphical){if(2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");return"single"===this.precision&&(console.warn("Cannot use graphical mode and single precision at the same time"),this.precision="unsigned"),void(this.texSize=a.clone(this.output))}!this.graphical&&null===this.precision&&t.isTextureFloat&&(this.precision="single"),this.texSize=a.getKernelTextureSize({optimizeFloatMemory:this.optimizeFloatMemory,precision:this.precision},this.output),this.checkTextureSize()}translateSource(){const e=n.fromKernel(this,r,{fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy});this.translatedSource=e.getPrototypeString("kernel"),this.setupReturnTypes(e)}drawBuffers(){this.context.drawBuffers(this.drawBuffersMap)}getTextureFormat(){const{context:e}=this;switch(this.getInternalFormat()){case e.R32F:return e.RED;case e.RG32F:return e.RG;case e.RGBA32F:case e.RGBA:return e.RGBA;default:throw new Error("Unknown internal format")}}renderValues(){return void 0===this._tightRead&&this._detectTightRead(),super.renderValues()}renderKernelsToArrays(){return void 0===this._tightRead&&this._detectTightRead(),super.renderKernelsToArrays()}readFloatPixelsToFloat32Array(){if(!this._tightRead)return super.readFloatPixelsToFloat32Array();const{texSize:e,context:t}=this,s=e[0],r=e[1],n=new Float32Array(s*r);return t.readPixels(0,0,s,r,t.RED,t.FLOAT,n),n}renderOutputAsync(){return this.renderOutput!==this.renderValues?Promise.resolve(this.renderOutput()):this.renderValuesAsync()}renderValuesAsync(){void 0===this._tightRead&&this._detectTightRead();const e=this.formatValues,[t,s,r]=this.output;return this.transferValuesAsync().then(n=>e(n,t,s,r))}transferValuesAsync(){const{texSize:e,context:t}=this,s=e[0],r=e[1];let n,i,a;"single"===this.precision?(n=this._tightRead?t.RED:t.RGBA,i=t.FLOAT,a=new Float32Array(s*r*(this._tightRead?1:4))):(n=t.RGBA,i=t.UNSIGNED_BYTE,a=new Uint8Array(s*r*4));const o=t.createBuffer();t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(0,0,s,r,n,i,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);const u=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),this._pollFence(u).then(()=>(t.bindBuffer(t.PIXEL_PACK_BUFFER,o),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,a),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.deleteBuffer(o),"single"===this.precision?a:new Float32Array(a.buffer)),e=>{throw t.deleteBuffer(o),e})}_pollFence(e){const t=this.context;return new Promise((s,r)=>{let n,i=null;"undefined"!=typeof MessageChannel?(i=new MessageChannel,i.port1.onmessage=()=>o(),n=()=>i.port2.postMessage(0)):n=()=>setTimeout(o,0);const a=(s,r)=>{t.deleteSync(e),i&&(i.port1.close(),i.port2.close()),s(r)},o=()=>{if(t.isContextLost())return a(r,new Error("WebGL context lost while awaiting kernel result"));const i=t.clientWaitSync(e,0,0);return i===t.ALREADY_SIGNALED||i===t.CONDITION_SATISFIED?a(s):i===t.WAIT_FAILED?a(r,new Error("clientWaitSync failed while awaiting kernel result")):void n()};o()})}_detectTightRead(){const e=this.context;this._tightRead=!1,e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t="Number"===this.returnType||"Float"===this.returnType||"Integer"===this.returnType||"LiteralInteger"===this.returnType;if("single"===this.precision&&!this.optimizeFloatMemory&&!this.graphical&&t&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)===e.RED&&e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)===e.FLOAT){if(this.formatValues===a.erectFloat)this.formatValues=a.erectMemoryOptimizedFloat;else if(this.formatValues===a.erect2DFloat)this.formatValues=a.erectMemoryOptimized2DFloat;else if(this.formatValues===a.erect3DFloat)this.formatValues=a.erectMemoryOptimized3DFloat;else if(this.formatValues!==a.erectMemoryOptimizedFloat&&this.formatValues!==a.erectMemoryOptimized2DFloat&&this.formatValues!==a.erectMemoryOptimized3DFloat)return;this._tightRead=!0}}getInternalFormat(){const{context:e}=this;if("single"===this.precision)switch(this.returnType){case"Number":case"Float":case"Integer":return this.optimizeFloatMemory?e.RGBA32F:e.R32F;case"Array(2)":return e.RG32F;case"Array(3)":case"Array(4)":return e.RGBA32F;default:throw new Error("Unhandled return type")}return e.RGBA}_setupOutputTexture(){const e=this.context;if(this.texture)return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0),void(this._tightRead=void 0);e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer);const t=e.createTexture(),s=this.texSize;e.activeTexture(e.TEXTURE0+this.constantTextureCount+this.argumentTextureCount),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST);const r=this.getInternalFormat();"single"===this.precision?e.texStorage2D(e.TEXTURE_2D,1,r,s[0],s[1]):e.texImage2D(e.TEXTURE_2D,0,r,s[0],s[1],0,r,e.UNSIGNED_BYTE,null),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.texture=new this.TextureConstructor({texture:t,size:s,dimensions:this.threadDim,output:this.output,context:this.context,internalFormat:this.getInternalFormat(),textureFormat:this.getTextureFormat(),kernel:this}),this._tightRead=void 0}_setupSubOutputTextures(){const e=this.context;if(this.mappedTextures){for(let t=0;t{const{utils:s}=i(),{FunctionNode:r}=l();const n={Number:"f32",Float:"f32",Integer:"i32",LiteralInteger:"f32",Boolean:"bool","Array(2)":"vec2","Array(3)":"vec3","Array(4)":"vec4"},a={"===":"==","!==":"!="},o=["x","y","z","w"],u={pow:"_pow",round:"_round"},h={ceil:!0,floor:!0,_round:!0};t.exports={WGSLFunctionNode:class extends r{get requiresSequenceFreeForInit(){return!0}wgslFloat(e){if(e===1/0)return"0x1.fffffep+127";if(e===-1/0)return"-0x1.fffffep+127";if(e>34028234663852886e22)return"0x1.fffffep+127";if(e<-34028234663852886e22)return"-0x1.fffffep+127";const t=`${e}`;return-1!==t.indexOf(".")||-1!==t.indexOf("e")||-1!==t.indexOf("E")?t:`${t}.0`}wgslInt(e){return`${Math.round(e)}`}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getLookupType(e){return"WebGPUBuffer"===e?"Number":super.getLookupType(e)}astUpdateExpression(e,t){return this.astGeneric(e.argument,t),t.push(e.operator),t}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}astConditionalExpression(e,t){if("ConditionalExpression"!==e.type)throw this.astErrorOutput("Not a conditional expression",e);const s=this.getType(e.consequent),r=this.getType(e.alternate);if(null===s&&null===r)return t.push("if ("),this.astGeneric(e.test,t),t.push(") {"),this.astGeneric(e.consequent,t),t.push(";"),t.push("} else {"),this.astGeneric(e.alternate,t),t.push(";"),t.push("}"),t;let n="LiteralInteger"===s?"Number":s;"Integer"!==n||"Number"!==r&&"Float"!==r||(n="Number");const i=e=>{const s=this.getType(e);switch(n){case"Number":case"Float":"Integer"===s?this.castValueToFloat(e,t):"LiteralInteger"===s?this.castLiteralToFloat(e,t):this.astGeneric(e,t);break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(e,t):"LiteralInteger"===s?this.castLiteralToInteger(e,t):this.astGeneric(e,t);break;default:this.astGeneric(e,t)}};return t.push("select("),i(e.alternate),t.push(", "),i(e.consequent),t.push(", "),this.astGeneric(e.test,t),t.push(")"),t}astFunction(e,t){if(this.isRootKernel){for(let s=0;s0&&t.push(", ");let a=this.argumentTypes[this.argumentNames.indexOf(i)];if(!a)throw this.astErrorOutput(`Unknown argument ${i} type`,e);"LiteralInteger"===a&&(this.argumentTypes[r]=a="Number");const o=n[a];if(!o)throw this.astErrorOutput(`WebGPU backend does not yet support ${a} arguments to helper functions`,e);t.push(`user_${s.sanitizeName(i)} : ${o}`)}t.push(")"),i&&t.push(` -> ${i}`),t.push(" {\n");for(let s=0;s>":!0,">>>":!0}[e.operator])return null;const s=e=>{switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;default:this.pushState("building-integer"),this.astGeneric(e,t),this.popState("building-integer")}};return t.push("("),">>>"===e.operator?(t.push("bitcast(bitcast("),s(e.left),t.push(") >> u32("),s(e.right),t.push("))")):"<<"===e.operator||">>"===e.operator?(s(e.left),t.push(` ${e.operator} u32(`),s(e.right),t.push(")")):(s(e.left),t.push(` ${e.operator} `),s(e.right)),t.push(")"),t}checkAndUpconvertBitwiseUnary(e,t){if("~"!==e.operator)return null;switch(t.push("~("),this.getType(e.argument)){case"Number":case"Float":this.castValueToInteger(e.argument,t);break;case"LiteralInteger":this.castLiteralToInteger(e.argument,t);break;default:this.astGeneric(e.argument,t)}return t.push(")"),t}astUnaryExpression(e,t){return this.checkAndUpconvertBitwiseUnary(e,t)?t:"+"===e.operator?(this.astGeneric(e.argument,t),t):(e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t)}castLiteralToInteger(e,t){return this.pushState("casting-to-integer"),this.astGeneric(e,t),this.popState("casting-to-integer"),t}castLiteralToFloat(e,t){return this.pushState("casting-to-float"),this.astGeneric(e,t),this.popState("casting-to-float"),t}castValueToInteger(e,t){return this.pushState("casting-to-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-integer"),t}castValueToFloat(e,t){return this.pushState("casting-to-float"),t.push("f32("),this.astGeneric(e,t),t.push(")"),this.popState("casting-to-float"),t}astIdentifierExpression(e,t){if("Identifier"!==e.type)throw this.astErrorOutput("IdentifierExpression - not an Identifier",e);const r=this.getType(e),n=s.sanitizeName(e.name);return"Infinity"===e.name?(t.push("0x1.fffffep+127"),t):!this.isRootKernel||-1===this.argumentNames.indexOf(e.name)||"Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r?(t.push(`user_${n}`),t):("Boolean"===r?t.push(`bool(params.user_${n})`):t.push(`params.user_${n}`),t)}astForStatement(e,t){if("ForStatement"!==e.type)throw this.astErrorOutput("Invalid for statement",e);const s=[],r=[],n=[],i=[];let a=null;if(e.init){const{declarations:t}=e.init;t.length>1&&(a=!1),this.astGeneric(e.init,s);for(let e=0;e0&&t.push(s.join(""),"\n"),t.push(`for (var ${e} : i32 = 0;${e}0&&t.push(`if (!(${r.join("")})) { break; }\n`),t.push(i.join("")),t.push(`\n${n.join("")};`),t.push("}\n")}return t}astWhileStatement(e,t){if("WhileStatement"!==e.type)throw this.astErrorOutput("Invalid while statement",e);const s=this.getInternalVariableName("safeI");return t.push(`for (var ${s} : i32 = 0;${s}{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(t);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const s in e)if("loc"!==s&&"range"!==s&&"parent"!==s&&t(e[s]))return!0;return!1};if(t(s[e]))throw this.astErrorOutput("break inside a switch case is only supported as the case terminator",s[e])}for(let e=0;ee+1){u=!0,this.astSwitchCaseConsequent(r[e].consequent,o);continue}t.push(" else {\n")}this.astSwitchCaseConsequent(r[e].consequent,t),t.push("\n}")}return u&&(t.push(" else {"),t.push(o.join("")),t.push("}")),t.push("\n"),t}astThisExpression(e,t){return t.push("this"),t}astSequenceExpression(e,t){const{expressions:s}=e;if(1===s.length)return this.astGeneric(s[0],t),t;throw this.astErrorOutput("WebGPU backend does not yet support the comma operator",e)}astMemberExpression(e,t){const{property:r,name:i,signature:a,origin:o,type:u,xProperty:l,yProperty:h,zProperty:c}=this.getMemberExpressionDetails(e);switch(a){case"value.thread.value":case"this.thread.value":if("x"!==i&&"y"!==i&&"z"!==i)throw this.astErrorOutput("Unexpected expression, expected `this.thread.x`, `this.thread.y`, or `this.thread.z`",e);return t.push(`i32(threadGid.${i})`),t;case"this.output.value":{const s={x:0,y:1,z:2}[i];if(void 0===s)throw this.astErrorOutput("Unexpected expression",e);if(this.dynamicOutput){const e=`params.output${i.toUpperCase()}`;this.isState("casting-to-float")?t.push(`f32(${e})`):t.push(`i32(${e})`)}else this.isState("casting-to-integer")?t.push(`${this.output[s]}`):t.push(`${this.output[s]}.0`);return t}case"value":throw this.astErrorOutput("Unexpected expression",e);case"value[]":case"value[][]":case"value[][][]":case"value[][][][]":case"value.value":if("Math"===o)return t.push(this.wgslFloat(Math[i])),t;switch(r){case"r":return t.push(`user_${s.sanitizeName(i)}.x`),t;case"g":return t.push(`user_${s.sanitizeName(i)}.y`),t;case"b":return t.push(`user_${s.sanitizeName(i)}.z`),t;case"a":return t.push(`user_${s.sanitizeName(i)}.w`),t}break;case"this.constants.value":{const s=this.constants[i];switch(u){case"Integer":return this.isState("casting-to-float")?t.push(this.wgslFloat(s)):t.push(this.wgslInt(s)),t;case"Number":case"Float":return this.isState("casting-to-integer")?t.push(this.wgslInt(s)):t.push(this.wgslFloat(s)),t;case"Boolean":return t.push(s?"true":"false"),t;case"Array(2)":case"Array(3)":case"Array(4)":{const e=parseInt(u.substring(6),10),r=[];for(let t=0;t4)throw this.astErrorOutput("this.color takes (r, g, b) or (r, g, b, a)",e);t.push("kernelColor(data_index");for(let s=0;s0&&t.push(", "),n){case"Integer":this.castValueToFloat(r,t);break;case"LiteralInteger":this.castLiteralToFloat(r,t);break;default:this.astGeneric(r,t)}}else{const n=this.lookupFunctionArgumentTypes(r)||[];for(let i=0;i0&&t.push(", ");const u=this.getType(a);switch(o||(this.triggerImplyArgumentType(r,i,u,this),o=u),u){case"Boolean":this.astGeneric(a,t);continue;case"Number":case"Float":if("Integer"===o){t.push("i32("),this.astGeneric(a,t),t.push(")");continue}if("Number"===o||"Float"===o){this.astGeneric(a,t);continue}if("LiteralInteger"===o){this.castLiteralToFloat(a,t);continue}break;case"Integer":if("Number"===o||"Float"===o){t.push("f32("),this.astGeneric(a,t),t.push(")");continue}if("Integer"===o){this.astGeneric(a,t);continue}break;case"LiteralInteger":if("Integer"===o){this.castLiteralToInteger(a,t);continue}if("Number"===o||"Float"===o){this.castLiteralToFloat(a,t);continue}if("LiteralInteger"===o){this.astGeneric(a,t);continue}break;case"Array(2)":case"Array(3)":case"Array(4)":if(o===u){"Identifier"===a.type?t.push(`user_${s.sanitizeName(a.name)}`):this.astGeneric(a,t);continue}break;case"Array":case"Array2D":case"Array3D":case"Input":case"WebGPUBuffer":throw this.astErrorOutput("WebGPU backend does not yet support array arguments to helper functions",e)}throw this.astErrorOutput(`Unhandled argument combination of ${u} and ${o} for argument named "${a.name}"`,e)}}return t.push(")"),a&&t.push(")"),t}astArrayExpression(e,t){switch(this.getType(e)){case"Matrix(2)":case"Matrix(3)":case"Matrix(4)":throw this.astErrorOutput("WebGPU backend does not yet support Matrix types",e)}const s=e.elements.length;t.push(`vec${s}(`);for(let r=0;r0&&t.push(", ");const s=e.elements[r];switch(this.getType(s)){case"Integer":this.castValueToFloat(s,t);break;case"LiteralInteger":this.castLiteralToFloat(s,t);break;default:this.astGeneric(s,t)}}return t.push(")"),t}memberExpressionXYZ(e,t,s,r){return s?r.push(this.memberExpressionPropertyMarkup(s),", "):r.push("0, "),t?r.push(this.memberExpressionPropertyMarkup(t),", "):r.push("0, "),r.push(this.memberExpressionPropertyMarkup(e)),r}memberExpressionPropertyMarkup(e){if(!e)throw new Error("Property not set");const t=[];switch(this.getType(e)){case"Number":case"Float":this.castValueToInteger(e,t);break;case"LiteralInteger":this.castLiteralToInteger(e,t);break;case"Integer":this.pushState("building-integer"),t.push("i32("),this.astGeneric(e,t),t.push(")"),this.popState("building-integer");break;default:this.astGeneric(e,t)}return t.join("")}}}}),rt=e((e,t)=>{let s=null;t.exports={WebGPUContext:class e{static get isSupported(){return"undefined"!=typeof navigator&&!!navigator.gpu}static acquire(){if(s)return s;const t=(async()=>{if(!e.isSupported)throw new Error("WebGPU is not supported on this platform (navigator.gpu is missing)");const r=await navigator.gpu.requestAdapter();if(!r)throw new Error("WebGPU is present (navigator.gpu) but no adapter is available. On headless Chromium there is no adapter; run headed. Use `await GPU.isWebGPUAvailable()` to feature-detect.");const n=await r.requestDevice({requiredLimits:{maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize}}),i={adapter:r,device:n,isLost:!1};return n.lost.then(e=>{i.isLost=!0,"destroyed"!==e.reason&&console.error(`gpu.js [webgpu]: device lost: ${e.message}`),s===t&&(s=null)}),n.onuncapturederror=e=>{console.error(`gpu.js [webgpu]: ${e.error.message}`)},i})();return t.catch(()=>{s===t&&(s=null)}),s=t}static destroy(){if(!s)return Promise.resolve();const e=s;return s=null,e.then(({device:e})=>{e.destroy()},()=>{})}}}}),nt=e((e,t)=>{t.exports={WebGPUBufferResult:class e{constructor(e){this.buffer=e.buffer,this.output=e.output,this.componentCount=e.componentCount||1,this.context=e.context,this.kernel=e.kernel,this.type="WebGPUBuffer",this._deleted=!1,this.buffer._refs?this.buffer._refs++:this.buffer._refs=1}toArray(){return this._deleted?Promise.reject(new Error("WebGPUBufferResult has been deleted")):this.kernel.readBufferResult(this)}delete(){this._deleted||(this._deleted=!0,0===--this.buffer._refs&&this.buffer.destroy())}clone(){return new e(this)}}}}),it=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WGSLFunctionNode:u}=st(),{WebGPUContext:l}=rt(),{WebGPUBufferResult:h}=nt(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0}),f={_pow:"fn _pow(v1 : f32, v2 : f32) -> f32 {\n if (v2 == 0.0) { return 1.0; }\n return pow(v1, v2);\n}",_round:"fn _round(x : f32) -> f32 {\n return floor(x + 0.5);\n}",cbrt:"fn cbrt(x : f32) -> f32 {\n return sign(x) * pow(abs(x), 1.0 / 3.0);\n}",expm1:"fn expm1(x : f32) -> f32 {\n return exp(x) - 1.0;\n}",fround:"fn fround(x : f32) -> f32 {\n return x;\n}",imul:"fn imul(a : f32, b : f32) -> f32 {\n return f32(i32(a) * i32(b));\n}",log10:`fn log10(x : f32) -> f32 {\n return log2(x) * ${1/Math.log2(10)};\n}`,log1p:"fn log1p(x : f32) -> f32 {\n return log(1.0 + x);\n}",clz32:"fn clz32(x : f32) -> f32 {\n return f32(countLeadingZeros(u32(x)));\n}"};t.exports={WebGPUKernel:class extends s{static get isSupported(){return l.isSupported}static get isAsync(){return!0}static isContextMatch(e){return Boolean(e&&"function"==typeof e.createShaderModule&&"function"==typeof e.createComputePipeline)}static getFeatures(){return d}static get features(){return d}static get mode(){return"webgpu"}static getSignature(e,t){return"webgpu"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static nativeFunctionArguments(){throw new Error("WebGPU backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebGPU backend does not yet support native functions")}static combineKernels(){throw new Error("WebGPU backend does not yet support combineKernels; chain kernels with `await` and pipeline mode instead")}constructor(e,t){if(super(e,t),t){if("unsigned"===t.precision&&!t.graphical)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(t.subKernels)throw new Error("WebGPU backend does not yet support createKernelMap")}this.mergeSettings(e.settings||t),(null===this.precision||this.graphical)&&(this.precision="single"),this.asyncMode=!0,this.threadDim=null,this.componentCount=1,this.compiledSource=null,this.translatedBody=null,this.translatedFunctions=null,this.paramsLayout=null,this._buildPromise=null,this._device=null,this.computePipeline=null,this.bindGroupLayout=null,this.bindGroup=null,this.bindGroupDirty=!0,this.paramsBuffer=null,this.paramsMirror=null,this.outputBuffer=null,this.argumentBuffers=null,this.constantBuffers=null,this.stagingPool=[],this._canvasContext=null,this._blitPipeline=null,this._blitParamsBuffer=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built){if(!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");if(t.length!==this.output.length)throw new Error("WebGPU backend does not yet support changing the output rank of a built kernel; the workgroup shape is fixed at build")}return this.output=t,this}toString(){throw new Error("WebGPU backend does not yet support toString")}validateSettings(e){if(this.graphical){if(!this.output||2!==this.output.length)throw new Error("Output must have 2 dimensions on graphical mode");if(this.pipeline)throw new Error("graphical mode and pipeline mode are mutually exclusive");if(!this.canvas)throw new Error("graphical mode requires a canvas (none could be created; pass one in settings)")}if("unsigned"===this.precision)throw new Error("WebGPU backend does not yet support precision: 'unsigned'; it is single precision only");if(this.precision="single",this.subKernels&&this.subKernels.length>0)throw new Error("WebGPU backend does not yet support createKernelMap");if(!this.output||0===this.output.length){if(1!==e.length)throw new Error("Auto output only supported for kernels with only one input");const t=c.getVariableType(e[0],this.strictIntegers);if("Array"===t)this.output=Array.from(c.getDimensions(e[0]));else{if("WebGPUBuffer"!==t)throw new Error("Auto output not supported for input type: "+t);this.output=Array.from(e[0].output)}}this.checkOutput()}setupArguments(e){super.setupArguments(e);for(let e=0;e,`);for(let e=0;e params : Params;");for(let t=0;t user_${e[t].name} : array;`);const i=1+e.length;r.push(`@group(0) @binding(${i}) var result : array;`),this.graphical&&r.push("fn kernelColor(index : i32, r : f32, g : f32, b : f32, a : f32) {\n result[index * 4] = r;\n result[index * 4 + 1] = g;\n result[index * 4 + 2] = b;\n result[index * 4 + 3] = a;\n}");for(let e=0;e constants_${s[e].name} : array;`);r.push("var threadGid : vec3;"),null!==this.paramsLayout.randomSeedOffset&&r.push("var pcgState : u32;\nfn pcg_random() -> f32 {\n pcgState = pcgState * 747796405u + 2891336453u;\n let word = ((pcgState >> ((pcgState >> 28u) + 4u)) ^ pcgState) * 277803737u;\n let mixed = (word >> 22u) ^ word;\n return f32(mixed >> 8u) / 16777216.0;\n}");const a=`${this.translatedFunctions}\n${this.translatedBody}`;/\bLOOP_MAX\b/.test(a)&&r.push(`const LOOP_MAX : i32 = ${parseInt(this.loopMaxIterations,10)||1e3};`);for(const e in f)new RegExp(`\\b${e}\\(`).test(a)&&r.push(f[e]);for(let t=0;t f32 {\n return user_${s}[u32(x + i32(params.user_${s}_dims.x) * (y + i32(params.user_${s}_dims.y) * z))];\n}`)}for(let e=0;e f32 {\n return constants_${t.name}[u32(x + ${i[0]} * (y + ${i[1]} * z))];\n}`)}this.translatedFunctions&&r.push(this.translatedFunctions);const o=1===this.output.length?[64,1,1]:[8,8,1];return this.workgroupSize=o,1===this.output.length?r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n let flat_index : u32 = gid.x + gid.y * params.dispatchWidth;\n threadGid = vec3(flat_index, 0u, 0u);\n if (flat_index >= params.outputX) { return; }\n let data_index : i32 = i32(flat_index);\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`):r.push(`@compute @workgroup_size(${o[0]}, ${o[1]}, ${o[2]})\nfn main(@builtin(global_invocation_id) gid : vec3) {\n threadGid = gid;\n if (gid.x >= params.outputX || gid.y >= params.outputY || gid.z >= params.outputZ) { return; }\n let data_index : i32 = i32(gid.x + params.outputX * (gid.y + params.outputY * gid.z));\n${null!==this.paramsLayout.randomSeedOffset?" pcgState = (params.randomSeed + u32(data_index) * 2654435769u) * 747796405u + 2891336453u;\n":""}${this.translatedBody}\n}`),r.join("\n")}constantDimensions(e){const t=e instanceof p?Array.from(e.size):Array.from(c.getDimensions(e));for(;t.length<3;)t.push(1);return t}async _buildAsync(){const e=await l.acquire();this.context=e;const t=this._device=e.device,s=t.createShaderModule({code:this.compiledSource}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling WGSL compute shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n")+`\n--- generated WGSL ---\n${this.compiledSource}`);const{arrayArgs:n,bufferConstants:i,byteLength:a}=this.paramsLayout,o=[{binding:0,visibility:4,buffer:{type:"uniform"}}];for(let e=0;ei&&(n[1]=Math.ceil(n[0]/i),n[0]=Math.ceil(n[0]/n[1])),a=n[0]*t);for(let e=0;e<3;e++)if(n[e]>i)throw new Error(`output dimension ${e} needs ${n[e]} workgroups, over this device's limit of ${i}`);return{groups:n,dispatchWidth:a}}async _buildBlitPipeline(e){if(this.canvas.width=this.output[0],this.canvas.height=this.output[1],this._canvasContext=this.canvas.getContext("webgpu"),!this._canvasContext)throw new Error("could not get a webgpu context from the canvas");const t=navigator.gpu.getPreferredCanvasFormat();this._canvasContext.configure({device:e,format:t,alphaMode:"premultiplied"});const s=e.createShaderModule({code:"struct BlitParams { width : u32, height : u32, pad0 : u32, pad1 : u32 }\n@group(0) @binding(0) var blit : BlitParams;\n@group(0) @binding(1) var pixels : array;\n@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4 {\n var pos = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n return vec4(pos[vi], 0.0, 1.0);\n}\n@fragment fn fs(@builtin(position) pos : vec4) -> @location(0) vec4 {\n let x = u32(pos.x);\n let y = u32(pos.y);\n let row = blit.height - 1u - y;\n let i = (row * blit.width + x) * 4u;\n let a = pixels[i + 3u];\n return vec4(pixels[i] * a, pixels[i + 1u] * a, pixels[i + 2u] * a, a);\n}"}),r=(await s.getCompilationInfo()).messages.filter(e=>"error"===e.type);if(r.length>0)throw new Error("Error compiling the graphical blit shader:\n"+r.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join("\n"));this._blitBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:2,buffer:{type:"uniform"}},{binding:1,visibility:2,buffer:{type:"read-only-storage"}}]}),this._blitPipeline=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[this._blitBindGroupLayout]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t}]},primitive:{topology:"triangle-list"}}),this._blitParamsBuffer=e.createBuffer({size:16,usage:72})}_ensureOutputBuffer(){const[e,t,s]=this.threadDim,r=e*t*s*4*this.componentCount;this.immutable&&this.pipeline&&this.outputBuffer&&(0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this.outputBuffer=null,this.bindGroupDirty=!0),this.outputBuffer&&this.outputBuffer.size>=r||(this.outputBuffer&&0===--this.outputBuffer._refs&&this.outputBuffer.destroy(),this._checkBufferSize(r,`output [${this.output.join(", ")}]`),this.outputBuffer=this._device.createBuffer({size:r,usage:132}),this.outputBuffer._refs=1,this.bindGroupDirty=!0)}_checkBufferSize(e,t){const s=this._device.limits,r=Math.min(s.maxStorageBufferBindingSize,s.maxBufferSize);if(e>r)throw new Error(`WebGPU backend: ${t} needs ${e} bytes but this device allows ${r} per storage buffer (maxStorageBufferBindingSize/maxBufferSize); reduce the output or split the work across kernels`)}_snapshotArguments(e){const t=new Array(e.length);for(let s=0;sthis._runInternal(e))}_runInternal(e){if(this.context&&this.context.isLost)throw new Error("WebGPU device was lost; call kernel.destroy() (or gpu.destroy()) and run again to rebuild on a fresh device");const t=this._device,s=t.queue,{arrayArgs:r,scalarArgs:n,bufferConstants:i}=this.paramsLayout,a=this.threadDim=Array.from(this.output);for(;a.length<3;)a.push(1);if(this._ensureOutputBuffer(),null!==this.paramsLayout.randomSeedOffset){const e=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0;this.paramsU32[this.paramsLayout.randomSeedOffset/4]=e}this.paramsU32[0]=a[0],this.paramsU32[1]=a[1],this.paramsU32[2]=a[2],this.paramsU32[3]=this._computeDispatch(a).dispatchWidth;for(let n=0;n{const e=new Float32Array(p.buffer.getMappedRange(0,u).slice(0));return p.buffer.unmap(),this._releaseStaging(p),this._shapeOutput(e,d,this.componentCount)},e=>{throw this._releaseStaging(p),e})}_acquireStaging(e){for(let t=0;t=e)return s.busy=!0,s}const t={buffer:this._device.createBuffer({size:e,usage:9}),size:e,busy:!0,pooled:this.stagingPool.length<3};return t.pooled&&this.stagingPool.push(t),t}_releaseStaging(e){e.pooled?e.busy=!1:e.buffer.destroy()}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const t=new Float32Array(i.buffer.getMappedRange(0,n).slice(0));return i.buffer.unmap(),this._releaseStaging(i),this._shapeOutput(t,s,e.componentCount)},e=>{throw this._releaseStaging(i),e})}getPixels(e){if(!this.graphical)return Promise.reject(new Error("getPixels only works on a graphical kernel"));if(!this.outputBuffer)return Promise.reject(new Error("run the kernel before reading its pixels"));const[t,s]=this.output,r=t*s*4*4,n=this._acquireStaging(r),i=this._device.createCommandEncoder();return i.copyBufferToBuffer(this.outputBuffer,0,n.buffer,0,r),this._device.queue.submit([i.finish()]),n.buffer.mapAsync(1,0,r).then(()=>{const i=new Float32Array(n.buffer.getMappedRange(0,r).slice(0));n.buffer.unmap(),this._releaseStaging(n);const a=new Uint8ClampedArray(t*s*4);for(let r=0;r{throw this._releaseStaging(n),e})}destroy(e){if(this._blitParamsBuffer&&(this._blitParamsBuffer.destroy(),this._blitParamsBuffer=null),this._canvasContext&&(this._canvasContext.unconfigure(),this._canvasContext=null),this._blitPipeline=null,this._blitBindGroup=null,this._blitBoundOutputBuffer=null,this.paramsBuffer&&(this.paramsBuffer.destroy(),this.paramsBuffer=null),this.paramsLayout)for(let e=0;e{const s={i32:127,i64:126,f32:125,f64:124,v128:123},r=new DataView(new ArrayBuffer(16));function n(e,t){let s=e>>>0;do{let e=127&s;s>>>=7,0!==s&&(e|=128),t.push(e)}while(0!==s)}function i(e,t){let s=0|e;for(;;){const e=127&s;if(s>>=7,0===s&&!(64&e)||-1===s&&64&e)return void t.push(e);t.push(128|e)}}function a(e,t,s){let r=e>>>0;for(let e=0;e<4;e++)t[s+e]=127&r|128,r>>>=7;t[s+4]=127&r}function o(e,t){const s=[];for(let t=0;t65535&&t++,r<128?s.push(r):r<2048?s.push(192|r>>6,128|63&r):r<65536?s.push(224|r>>12,128|r>>6&63,128|63&r):s.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}n(s.length,t);for(let e=0;e3)throw new Error(`WasmModuleBuilder: lane index ${t} out of range for 4-lane shape`);return this.bytes.push(253,e,t),this}_push(e){for(let t=0;t${t.join(",")}`;if(s in this.typeIndexByKey)return this.typeIndexByKey[s];const r=this.types.length;return this.types.push({params:e,results:t}),this.typeIndexByKey[s]=r,r}addMemoryImport(e,t,s=!1){if(s&&null==t)throw new Error("WasmModuleBuilder: shared memory import requires a maximum");return this.memoryImport={initial:e,maximum:t,shared:s},this}addFuncImport(e,t,s,r="env"){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);const n=this.funcImports.length;return this.funcImports.push({name:e,module:r,typeIndex:this._typeIndex(t,s)}),this.funcImportIndexByName[e]=n,n}addGlobal(e,t,s){return u(e),this.globals.push({type:e,mutable:t,initialValue:s}),this.globals.length-1}addFunction(e,{params:t=[],results:s=[],locals:r=[]}={}){if(e in this.funcImportIndexByName||e in this.functionIndexByName)throw new Error(`WasmModuleBuilder: duplicate function name "${e}"`);t.forEach(u),s.forEach(u),r.forEach(u);const n=new h(this,e,t,s,r);return this.functionIndexByName[e]=this.functions.length,this.functions.push({name:e,emitter:n,typeIndex:this._typeIndex(t,s)}),n}exportFunction(e,t=e){return this.exports.push({name:e,exportName:t}),this}_resolveFuncIndex(e){if(e in this.funcImportIndexByName)return this.funcImportIndexByName[e];if(e in this.functionIndexByName)return this.funcImports.length+this.functionIndexByName[e];throw new Error(`WasmModuleBuilder: call target "${e}" is not an import or a defined function`)}_section(e,t,s){s.push(e),n(t.length,s);for(let e=0;e0){const t=[];n(this.types.length,t);for(const{params:e,results:s}of this.types){t.push(96),n(e.length,t);for(const s of e)t.push(u(s));n(s.length,t);for(const e of s)t.push(u(e))}this._section(1,t,e)}if(null!==this.memoryImport||this.funcImports.length>0){const t=[];if(n((null!==this.memoryImport?1:0)+this.funcImports.length,t),null!==this.memoryImport){const{initial:e,maximum:s,shared:r}=this.memoryImport;o("env",t),o("memory",t),t.push(2);const i=null!=s;t.push(r?3:i?1:0),n(e,t),i&&n(s,t)}for(const{name:e,module:s,typeIndex:r}of this.funcImports)o(s,t),o(e,t),t.push(0),n(r,t);this._section(2,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{typeIndex:e}of this.functions)n(e,t);this._section(3,t,e)}if(this.globals.length>0){const t=[];n(this.globals.length,t);for(const{type:e,mutable:s,initialValue:n}of this.globals){if(t.push(u(e),s?1:0),"i32"===e)t.push(65),i(n,t);else if("f32"===e){t.push(67),r.setFloat32(0,n,!0);for(let e=0;e<4;e++)t.push(r.getUint8(e))}else{if("v128"!==e)throw new Error(`WasmModuleBuilder: no initializer encoding for global type "${e}"`);t.push(253,12);for(let e=0;e<16;e++)t.push(0)}t.push(11)}this._section(6,t,e)}if(this.exports.length>0){const t=[];n(this.exports.length,t);for(const{name:e,exportName:s}of this.exports)o(s,t),t.push(0),n(this._resolveFuncIndex(e),t);this._section(7,t,e)}if(this.functions.length>0){const t=[];n(this.functions.length,t);for(const{emitter:e}of this.functions){const s=e.bytes.slice();for(const{at:t,name:r}of e.callFixups)a(this._resolveFuncIndex(r),s,t);const r=[],i=[];for(const t of e.locals){const e=u(t);i.length>0&&i[i.length-1].type===e?i[i.length-1].count++:i.push({type:e,count:1})}n(i.length,r);for(const{type:e,count:t}of i)n(t,r),r.push(e);for(let e=0;e{const{utils:s}=i(),{FunctionNode:r}=l(),{WasmFunctionEmitter:n}=at();var a=class{constructor(){this.localCount=0}addLocal(){return this.localCount++}};for(const e of Object.getOwnPropertyNames(n.prototype))"constructor"!==e&&"addLocal"!==e&&"function"==typeof n.prototype[e]&&(a.prototype[e]=function(){return this});const o={sin:1,cos:1,tan:1,asin:1,acos:1,atan:1,atan2:2,sinh:1,cosh:1,tanh:1,asinh:1,acosh:1,atanh:1,exp:1,expm1:1,log:1,log2:1,log10:1,log1p:1,cbrt:1,pow:2,sign:1},u={abs:"f32Abs",floor:"f32Floor",ceil:"f32Ceil",sqrt:"f32Sqrt",trunc:"f32Trunc"},h={"+":"f32Add","-":"f32Sub","*":"f32Mul"},c={"+":"i32Add","-":"i32Sub","*":"i32Mul"},p={"==":"f32Eq","===":"f32Eq","!=":"f32Ne","!==":"f32Ne","<":"f32Lt",">":"f32Gt","<=":"f32Le",">=":"f32Ge"},d={"==":"i32Eq","===":"i32Eq","!=":"i32Ne","!==":"i32Ne","<":"i32LtS",">":"i32GtS","<=":"i32LeS",">=":"i32GeS"},f={"&":"i32And","|":"i32Or","^":"i32Xor","<<":"i32Shl",">>":"i32ShrS",">>>":"i32ShrU"},m={"+":"f32x4Add","-":"f32x4Sub","*":"f32x4Mul"},g={"+":"i32x4Add","-":"i32x4Sub","*":"i32x4Mul"},y={"==":"f32x4Eq","===":"f32x4Eq","!=":"f32x4Ne","!==":"f32x4Ne","<":"f32x4Lt",">":"f32x4Gt","<=":"f32x4Le",">=":"f32x4Ge"},x={"==":"i32x4Eq","===":"i32x4Eq","!=":"i32x4Ne","!==":"i32x4Ne","<":"i32x4LtS",">":"i32x4GtS","<=":"i32x4LeS",">=":"i32x4GeS"},b={"<<":"i32x4Shl",">>":"i32x4ShrS",">>>":"i32x4ShrU"},v={abs:"f32x4Abs",floor:"f32x4Floor",ceil:"f32x4Ceil",sqrt:"f32x4Sqrt",trunc:"f32x4Trunc"};function S(e){switch(e){case"Number":case"Float":case"LiteralInteger":return"f32";case"Integer":case"Boolean":return"i32";default:throw new Error(`WebAssembly backend does not yet support ${e} arguments to helper functions`)}}t.exports={WebAssemblyFunctionNode:class extends r{constructor(e,t){super(e,t),this.assembler=null,this.em=null,this.locals=null,this.depth=0,this.loopStack=null,this.usedMathImports=new Set,this.usesRandom=!1,this.readsThread=!1,this.taintedLocals=null,this.uniformity=[],this._analysisDone=!1,this._analysisPass=!1,this.vec=!1,this.vMaskDepth=0,this.vCur=-1,this.vRetMask=-1,this.vTerminated=!1,this.vInfo=null,this._vBaseX=-1}mangleFunctionName(e){return`fn_${s.sanitizeName(e)}`}getType(e){if(e&&"ConditionalExpression"===e.type){const t=this.getType(e.consequent);if("Integer"===t||"LiteralInteger"===t){const t=this.getType(e.alternate);if("Number"===t||"Float"===t)return"Number"}}return super.getType(e)}toString(){return this._analysisDone||(this._analysisDone=!0,this._analysisPass=!0,this.walkFunction(new a),this._analysisPass=!1),""}emitFunction(e){this.assembler=e;const{module:t}=e;let s;if(this.isRootKernel)s=t.addFunction("kernel",{params:[],results:[]});else{const e=this.argumentTypes.map(e=>S("LiteralInteger"===e?"Number":e)),r=[];if(this.returnType)switch(this.returnType){case"Integer":case"Boolean":r.push("i32");break;case"Number":case"Float":case"LiteralInteger":r.push("f32");break;default:throw new Error(`WebAssembly backend does not yet support helper functions returning ${this.returnType}`)}s=t.addFunction(this.mangleFunctionName(this.name),{params:e,results:r})}return this.walkFunction(s),!this.isRootKernel&&this.returnType&&s.unreachable(),s}walkFunction(e){this.em=e,this.locals=new Map,this.depth=0,this.loopStack=[],this.taintedLocals=new Set;const t=this.getJsAST();if(this.isRootKernel)for(const s of this.collectAssignedArgumentNames(t)){const t=this.argumentNames.indexOf(s),r=this.argumentTypes[t];if("Number"!==r&&"Float"!==r&&"Integer"!==r&&"Boolean"!==r)continue;const n=this.assembler?this.assembler.layout.scalars[s]:null,i=n?n.offset:0,a="Integer"===r||"Boolean"===r?"i32":"f32",o=e.addLocal(a);e.i32Const(0),"i32"===a?e.i32Load(i):e.f32Load(i),e.localSet(o),this.locals.set(s,{kind:"scalar",index:o,wtype:a,gtype:r})}if(!this.isRootKernel){for(let e=0;e{if(r&&"object"==typeof r){if(Array.isArray(r))return r.forEach(s);if("FunctionDeclaration"!==r.type||r===e){"AssignmentExpression"===r.type&&"Identifier"===r.left.type&&-1!==this.argumentNames.indexOf(r.left.name)&&t.add(r.left.name),"UpdateExpression"===r.type&&"Identifier"===r.argument.type&&-1!==this.argumentNames.indexOf(r.argument.name)&&t.add(r.argument.name);for(const e in r){if("loc"===e||"start"===e||"end"===e||"parent"===e)continue;const t=r[e];t&&"object"==typeof t&&s(t)}}}};return s(e.body),t}enterBlock(e){this.em.block(e),this.depth++}enterLoop(e){this.em.loop(e),this.depth++}enterIf(e){this.em.if_(e),this.depth++}exit(){this.em.end(),this.depth--}brTo(e){this.em.br(this.depth-e)}brIfTo(e){this.em.brIf(this.depth-e)}get loopMax(){return parseInt(this.loopMaxIterations,10)||1e3}coerce(e,t){if(e===t)return t;if("void"===e)throw new Error("cannot use a void expression as a value");switch(t){case"f32":return this.em.f32ConvertI32S(),"f32";case"i32":return"f32"===e&&this.em.i32TruncSatF32S(),"i32";case"bool":return"f32"===e?this.em.f32Const(0).f32Ne():this.em.i32Eqz().i32Eqz(),"bool";default:throw new Error(`unknown wasm value category ${t}`)}}castLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castLiteralToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}castValueToInteger(e){this.pushState("casting-to-integer");const t=this.expression(e);return this.popState("casting-to-integer"),this.coerce(t,"i32"),"i32"}castValueToFloat(e){this.pushState("casting-to-float");const t=this.expression(e);return this.popState("casting-to-float"),this.coerce(t,"f32"),"f32"}emitByType(e,t){const s=this.getType(e);return"f32"===t?"Integer"===s?this.castValueToFloat(e):"LiteralInteger"===s?this.castLiteralToFloat(e):(this.coerce(this.expression(e),"f32"),"f32"):"Number"===s||"Float"===s?this.castValueToInteger(e):"LiteralInteger"===s?this.castLiteralToInteger(e):(this.coerce(this.expression(e),"i32"),"i32")}emitCondition(e){const t=this.expression(e);if("bool"!==t)if("i32"!==t){if("f32"!==t)throw this.astErrorOutput("cannot use a void expression as a condition",e);this.em.f32Const(0).f32Ne()}else this.em.i32Eqz().i32Eqz()}statement(e){switch(e.type){case"VariableDeclaration":return this.stmtVariableDeclaration(e);case"ExpressionStatement":return this.statementExpression(e.expression);case"ReturnStatement":return this.stmtReturn(e);case"IfStatement":return this.stmtIf(e);case"ForStatement":return this.stmtFor(e);case"WhileStatement":return this.stmtWhile(e);case"DoWhileStatement":return this.stmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.castValueToFloat(n));else switch(i.valueType=u,u){case"Number":case"Float":this.setScalarLocal(o,"f32",u,()=>{"LiteralInteger"===a?this.castLiteralToFloat(n):"Integer"===a?this.castValueToFloat(n):this.coerce(this.expression(n),"f32")});break;case"Integer":this.setScalarLocal(o,"i32","Integer",()=>{"LiteralInteger"===a?this.castLiteralToInteger(n):"Number"===a||"Float"===a?this.castValueToInteger(n):this.coerce(this.expression(n),"i32")});break;case"Boolean":this.setScalarLocal(o,"i32","Boolean",()=>this.emitCondition(n));break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${u}`,e)}this.isThreadDependent(n)&&this.taintedLocals.add(o)}}setScalarLocal(e,t,s,r){let n=this.locals.get(e);n&&"scalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"scalar",index:this.em.addLocal(t),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.em.localSet(n.index)}declareVecLocal(e,t,s,r,n){const i=parseInt(t.substring(6),10);r.valueType=t;let a=this.locals.get(e);if(!a||"vec"!==a.kind||a.n!==i){const s=[];for(let e=0;ethis.em.localSet(s.index);else{if(s||!this.isRootKernel||-1===this.argumentNames.indexOf(t))throw this.astErrorOutput(`cannot assign to "${t}"`,e);{const s=this.argumentTypes[this.argumentNames.indexOf(t)],i=this.assembler?this.assembler.layout.scalars[t]:null;if(this.assembler&&!i)throw this.astErrorOutput(`WebAssembly backend does not yet support assigning to the array argument "${t}"`,e);const a=i?i.offset:0;r="Integer"===s||"Boolean"===s?"i32":"f32",this.em.i32Const(0),n=()=>"i32"===r?this.em.i32Store(a):this.em.f32Store(a)}}if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.castValueToFloat(e.right),this.coerce("f32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.castLiteralToFloat(e.right),this.coerce("f32",r)):"Integer"===t&&"LiteralInteger"===s?(this.castLiteralToInteger(e.right),this.coerce("i32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.coerce(this.expression(e.right),r):(this.castValueToInteger(e.right),this.coerce("i32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.coerce(this.exprBinary(t),r)}n(),(this.isThreadDependent(e.right)||"="!==e.operator&&this.taintedLocals.has(t))&&this.taintedLocals.add(t)}emitUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(!s||"scalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r="i32"===s.wtype,n=()=>r?this.em.i32Const(1):this.em.f32Const(1),i="++"===e.operator?r?"i32Add":"f32Add":r?"i32Sub":"f32Sub";return t?(this.em.localGet(s.index),n(),this.em[i]().localSet(s.index),"void"):(e.prefix?(this.em.localGet(s.index),n(),this.em[i]().localTee(s.index)):(this.em.localGet(s.index).localGet(s.index),n(),this.em[i]().localSet(s.index)),s.wtype)}stmtReturn(e){if(!e.argument){if(this.isRootKernel)return void this.em.return_();throw this.astErrorOutput("Unexpected return statement",e)}this.pushState("skip-literal-correction");const t=this.getType(e.argument);if(this.popState("skip-literal-correction"),this.returnType||(this.returnType="LiteralInteger"===t||"Integer"===t?"Number":t),this.isRootKernel)return this.stmtRootReturn(e,t);if(this.isSubKernel)throw this.astErrorOutput("WebAssembly backend does not yet support createKernelMap",e);switch(this.returnType){case"LiteralInteger":case"Number":case"Float":"Integer"===t?this.castValueToFloat(e.argument):"LiteralInteger"===t?this.castLiteralToFloat(e.argument):this.coerce(this.expression(e.argument),"f32");break;case"Integer":"Float"===t||"Number"===t?this.castValueToInteger(e.argument):"LiteralInteger"===t?this.castLiteralToInteger(e.argument):this.coerce(this.expression(e.argument),"i32");break;case"Boolean":this.emitCondition(e.argument);break;default:throw this.astErrorOutput(`unhandled return type ${this.returnType}`,e)}this.em.return_()}stmtRootReturn(e,t){const s=this.assembler?this.assembler.globals:{dataIndex:0},r=this.assembler?this.assembler.layout.outputOffset:0;switch(this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const t=parseInt(this.returnType.substring(6),10),n=e.argument;if("ArrayExpression"===n.type){if(n.elements.length!==t)throw this.astErrorOutput(`expected ${t} array elements to match return type ${this.returnType}`,e);for(let e=0;e1&&(t=!1);for(let e=0;e{if(e===a.length)return o&&this.emitSwitchConsequent(o),!1;const{tests:t,consequent:s}=a[e];for(let e=0;e0&&this.em.i32Or();return this.enterIf(),this.emitSwitchConsequent(s),(e+10&&(s.push({tests:r,consequent:e[n].consequent}),r=[])):t=e[n].consequent;return{groups:s,defaultConsequent:t}}collectSwitchCaseStatements(e){const t=[];for(let s=0;s{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(s);if("BreakStatement"===e.type)return!0;if("ForStatement"===e.type||"WhileStatement"===e.type||"DoWhileStatement"===e.type||"SwitchStatement"===e.type)return!1;for(const t in e)if("loc"!==t&&"range"!==t&&"parent"!==t&&s(e[t]))return!0;return!1};for(let e=0;e{const s=this.getType(t);switch(r){case"Number":case"Float":"Integer"===s?this.castValueToFloat(t):"LiteralInteger"===s?this.castLiteralToFloat(t):this.coerce(this.expression(t),"f32");break;case"Integer":"Number"===s||"Float"===s?this.castValueToInteger(t):"LiteralInteger"===s?this.castLiteralToInteger(t):this.coerce(this.expression(t),"i32");break;case"Boolean":this.emitCondition(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${r}`,e)}};return this.emitCondition(e.test),this.enterIf(n),i(e.consequent),this.em.else_(),i(e.alternate),this.exit(),"Boolean"===r?"bool":n}exprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);if(this.calledFunctions.indexOf(t)<0&&this.calledFunctions.push(t),this.onFunctionCall&&this.onFunctionCall(this.name,t,e.arguments),s)return this.emitMathCall(t,e);const r=this.getType(e),n=this.lookupFunctionArgumentTypes(t)||[];for(let s=0;s{switch(this.getType(e)){case"Integer":this.castValueToFloat(e);break;case"LiteralInteger":this.castLiteralToFloat(e);break;default:this.coerce(this.expression(e),"f32")}},r=u[e];if(r)return s(t.arguments[0]),this.em[r](),"f32";switch(e){case"round":return s(t.arguments[0]),this.em.f32Const(.5).f32Add().f32Floor(),"f32";case"fround":return s(t.arguments[0]),"f32";case"min":case"max":{const r="min"===e?"f32Min":"f32Max";s(t.arguments[0]);for(let e=1;e0&&this.emitClampScalarIndex(a.dims[0]*a.dims[1]*a.dims[2]-1),this.em.i32Const(2).i32Shl(),this.em.f32Load(a.offset),"f32"}emitClampScalarIndex(e){const t=this.em.addLocal("i32");this.em.localSet(t),this.em.localGet(t).i32Const(0).localGet(t).i32Const(0).i32GeS().select(),this.em.localSet(t),this.em.localGet(t).i32Const(e).localGet(t).i32Const(e).i32LeS().select()}emitVecIndex(e,t){if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return this.em.localGet(e.indices[t.value]),"f32"}const s=this.em.addLocal("i32");this.emitIndex(t),this.em.localSet(s),this.em.localGet(e.indices[0]);for(let t=1;t{if(!e||"object"!=typeof e)return!1;switch(e.type){case"Literal":case"ThisExpression":return!1;case"Identifier":return t.has(e.name);case"MemberExpression":return e.computed||"MemberExpression"!==e.object.type||e.object.computed||!e.object.property||"thread"!==e.object.property.name?e.computed?a(e.object)||a(e.property):a(e.object):"x"===e.property.name;case"BinaryExpression":case"LogicalExpression":return a(e.left)||a(e.right);case"UnaryExpression":case"UpdateExpression":return a(e.argument);case"ConditionalExpression":return a(e.test)||a(e.consequent)||a(e.alternate);case"CallExpression":return!i.isAstMathFunction(e)||("random"===e.callee.property.name||e.arguments.some(a));case"SequenceExpression":return e.expressions.some(a);case"ArrayExpression":return e.elements.some(a);case"AssignmentExpression":return a(e.right)||"Identifier"===e.left.type&&t.has(e.left.name);default:return!0}},o=e=>{e&&!t.has(e)&&(t.add(e),n=!0)},u=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>u(e,t));switch(e.type){case"UpdateExpression":return"Identifier"===e.argument.type&&(-1!==i.argumentNames.indexOf(e.argument.name)&&(s.has(e.argument.name)||(s.add(e.argument.name),n=!0),o(e.argument.name)),t&&o(e.argument.name)),u(e.argument,t);case"AssignmentExpression":return"Identifier"===e.left.type&&(-1!==i.argumentNames.indexOf(e.left.name)&&(s.has(e.left.name)||(s.add(e.left.name),n=!0),o(e.left.name)),t&&o(e.left.name)),u(e.left,t),u(e.right,t);case"ConditionalExpression":{u(e.test,t);const s=t||a(e.test);return u(e.consequent,s),u(e.alternate,s)}case"LogicalExpression":return u(e.left,t),u(e.right,!0);default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&u(r,t)}}}},l=(e,t)=>{if(e&&"object"==typeof e){if(Array.isArray(e))return e.forEach(e=>l(e,t));switch(e.type){case"VariableDeclarator":e.id&&"Identifier"===e.id.type&&t.push(e.id.name);break;case"AssignmentExpression":"Identifier"===e.left.type&&t.push(e.left.name);break;case"UpdateExpression":"Identifier"===e.argument.type&&t.push(e.argument.name);break;case"FunctionDeclaration":return}for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];r&&"object"==typeof r&&l(r,t)}}},h=(e,t)=>{if(!e||"object"!=typeof e)return!1;if(Array.isArray(e))return e.some(e=>h(e,t));switch(e.type){case"BreakStatement":case"ContinueStatement":return t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return!1;case"IfStatement":{const s=t||a(e.test);return!!h(e.consequent,s)||!!e.alternate&&h(e.alternate,s)}case"ConditionalExpression":{const s=t||a(e.test);return h(e.consequent,s)||h(e.alternate,s)}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));return e.cases.some(e=>e.consequent.some(e=>"BreakStatement"!==e.type&&h(e,s)))}default:for(const s in e){if("loc"===s||"start"===s||"end"===s||"parent"===s)continue;const r=e[s];if(r&&"object"==typeof r&&h(r,t))return!0}return!1}},c=(e,r)=>{switch(e.type){case"AssignmentExpression":if("Identifier"===e.left.type){const u=e.left.name;-1!==i.argumentNames.indexOf(u)&&(s.has(u)||(s.add(u),n=!0),o(u)),(r||a(e.right)||"="!==e.operator&&t.has(u))&&o(u)}return u(e.right,r);case"UpdateExpression":if("Identifier"===e.argument.type){const t=e.argument.name;-1!==i.argumentNames.indexOf(t)&&(s.has(t)||(s.add(t),n=!0),o(t)),r&&o(t)}return;case"SequenceExpression":return e.expressions.forEach(e=>c(e,r));default:return u(e,r)}},p=(e,t)=>{if(e)switch(e.type){case"VariableDeclaration":for(const s of e.declarations)s.init&&((t||a(s.init))&&o(s.id.name),u(s.init,t));return;case"ExpressionStatement":return c(e.expression,t);case"ReturnStatement":return t&&(r=!0),void(e.argument&&u(e.argument,t));case"IfStatement":{u(e.test,t);const s=t||a(e.test);return p(e.consequent,s),void(e.alternate&&p(e.alternate,s))}case"ForStatement":case"WhileStatement":case"DoWhileStatement":{const s=t||!!e.test&&a(e.test)||h(e.body,!1);if(s){const t=[];e.init&&l(e.init,t),l(e.body,t),e.update&&l(e.update,t),t.forEach(o)}return e.init&&("VariableDeclaration"===e.init.type?p(e.init,t):c(e.init,t)),p(e.body,s),e.update&&c(e.update,s),void(e.test&&u(e.test,s))}case"SwitchStatement":{const s=t||a(e.discriminant)||e.cases.some(e=>e.test&&a(e.test));for(const t of e.cases)for(const e of t.consequent)p(e,s);return}case"BlockStatement":return e.body.forEach(e=>p(e,t));default:return}};for(;n;)n=!1,p(e.body,!1);return{varying:t,varyingReturn:r,assignedArgs:s,exprVarying:a,hasVaryingExit:h}}vZero(){return this.em.v128ConstI32x4(0,0,0,0),this}vInnermostVaryingLoop(){const e=this.vLoopStack[this.vLoopStack.length-1];return e&&e.varying?e:null}vRecomputeCur(e){const t=this.em;t.localGet(e),-1!==this.vRetMask&&t.localGet(this.vRetMask).v128Andnot();const s=this.vInnermostVaryingLoop();s&&(-1!==s.vBrk&&t.localGet(s.vBrk).v128Andnot(),-1!==s.vCnt&&t.localGet(s.vCnt).v128Andnot()),t.localSet(this.vCur)}vLoopBodyExits(e){let t=!1,s=!1;const r=e=>{if(!(!e||"object"!=typeof e||t&&s)){if(Array.isArray(e))return e.forEach(r);switch(e.type){case"BreakStatement":return void(t=!0);case"ContinueStatement":return void(s=!0);case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"FunctionDeclaration":return;case"SwitchStatement":for(const t of e.cases)for(const e of t.consequent)"BreakStatement"!==e.type&&r(e);return}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];s&&"object"==typeof s&&r(s)}}};return r(e),{hasBreak:t,hasContinue:s}}vSetLocal(e){const t=this.em;this.vMaskDepth>0&&t.localGet(e).localGet(this.vCur).v128Bitselect(),t.localSet(e)}vCoerce(e,t){if(e===t)return t;const s=this.em;switch(e){case"f32":case"i32":case"bool":if("vf32"===t)return this.coerce(e,"f32"),s.f32x4Splat(),t;if("vi32"===t)return this.coerce(e,"i32"),s.i32x4Splat(),t;if("vbool"===t)return this.coerce(e,"i32"),s.i32x4Splat(),this.vZero(),s.i32x4Ne(),t;break;case"vf32":if("vi32"===t)return s.i32x4TruncSatF32x4S(),t;if("vbool"===t)return s.v128ConstF32x4(0,0,0,0).f32x4Ne(),t;break;case"vi32":if("vf32"===t)return s.f32x4ConvertI32x4S(),t;if("vbool"===t)return this.vZero(),s.i32x4Ne(),t;break;case"vbool":if("vi32"===t)return s.v128ConstI32x4(1,1,1,1).v128And(),t;if("vf32"===t)return s.v128ConstI32x4(1,1,1,1).v128And().f32x4ConvertI32x4S(),t}throw new Error(`cannot convert ${e} to ${t}`)}vCastLiteralToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastLiteralToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vCastValueToInteger(e){this.pushState("casting-to-integer");const t=this.vexpr(e);return this.popState("casting-to-integer"),this.vCoerce(t,"vi32"),"vi32"}vCastValueToFloat(e){this.pushState("casting-to-float");const t=this.vexpr(e);return this.popState("casting-to-float"),this.vCoerce(t,"vf32"),"vf32"}vEmitByType(e,t){const s=this.getType(e);return"vf32"===t?"Integer"===s?this.vCastValueToFloat(e):"LiteralInteger"===s?this.vCastLiteralToFloat(e):(this.vCoerce(this.vexpr(e),"vf32"),"vf32"):"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):(this.vCoerce(this.vexpr(e),"vi32"),"vi32")}vexprMask(e){const t=this.vexpr(e);if("vbool"!==t)return"vi32"===t?(this.vZero(),void this.em.i32x4Ne()):void("vf32"!==t?(this.coerce(t,"bool"),this.em.i32x4Splat(),this.vZero(),this.em.i32x4Ne()):this.em.v128ConstF32x4(0,0,0,0).f32x4Ne())}vstatement(e){switch(e.type){case"VariableDeclaration":return this.vstmtVariableDeclaration(e);case"ExpressionStatement":return this.vstatementExpression(e.expression);case"ReturnStatement":return this.vstmtReturn(e);case"IfStatement":return this.vstmtIf(e);case"ForStatement":return this.vstmtFor(e);case"WhileStatement":return this.vstmtWhile(e);case"DoWhileStatement":return this.vstmtDoWhile(e);case"BlockStatement":for(let t=0;tthis.vCastValueToFloat(r));switch(i.valueType=o,o){case"Number":case"Float":this.vSetVaryingScalar(n,"vf32",o,()=>{"LiteralInteger"===a?this.vCastLiteralToFloat(r):"Integer"===a?this.vCastValueToFloat(r):this.vCoerce(this.vexpr(r),"vf32")});break;case"Integer":this.vSetVaryingScalar(n,"vi32","Integer",()=>{"LiteralInteger"===a?this.vCastLiteralToInteger(r):"Number"===a||"Float"===a?this.vCastValueToInteger(r):this.vCoerce(this.vexpr(r),"vi32")});break;case"Boolean":this.vSetVaryingScalar(n,"vi32","Boolean",()=>{this.vexprMask(r),this.em.v128ConstI32x4(1,1,1,1).v128And()});break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support declaring type ${o}`,t)}}vSetVaryingScalar(e,t,s,r){let n=this.locals.get(e);n&&"vscalar"===n.kind&&n.wtype===t?n.gtype=s:(n={kind:"vscalar",index:this.em.addLocal("v128"),wtype:t,gtype:s},this.locals.set(e,n)),r(),this.vSetLocal(n.index)}vEmitArrayElement(e){switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}}vAssign(e){if("Identifier"!==e.left.type)throw this.astErrorOutput(`WebAssembly backend does not yet support assignment to ${e.left.type}`,e);const t=e.left.name,s=this.locals.get(t);if(s&&"scalar"===s.kind)return this.emitAssignment(e);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot assign to "${t}"`,e);const r=s.wtype;if("="===e.operator){const t=this.getType(e.left),s=this.getType(e.right);"Integer"!==t&&"Integer"===s?(this.vCastValueToFloat(e.right),this.vCoerce("vf32",r)):"Integer"!==t&&"LiteralInteger"===s?(this.vCastLiteralToFloat(e.right),this.vCoerce("vf32",r)):"Integer"===t&&"LiteralInteger"===s?(this.vCastLiteralToInteger(e.right),this.vCoerce("vi32",r)):"Integer"!==t||"Number"!==s&&"Float"!==s?this.vCoerce(this.vexpr(e.right),r):(this.vCastValueToInteger(e.right),this.vCoerce("vi32",r))}else{const t={type:"BinaryExpression",operator:e.operator.slice(0,-1),left:e.left,right:e.right};this.vCoerce(this.vexprBinary(t),r)}this.vSetLocal(s.index)}vUpdate(e,t){if("Identifier"!==e.argument.type)throw this.astErrorOutput("update expression needs a variable",e);const s=this.locals.get(e.argument.name);if(s&&"scalar"===s.kind)return this.emitUpdate(e,t);if(!s||"vscalar"!==s.kind)throw this.astErrorOutput(`cannot update "${e.argument.name}"`,e);const r=this.em,n="vi32"===s.wtype,i=()=>n?r.v128ConstI32x4(1,1,1,1):r.v128ConstF32x4(1,1,1,1),a="++"===e.operator?n?"i32x4Add":"f32x4Add":n?"i32x4Sub":"f32x4Sub";if(t)return r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),"void";if(e.prefix)r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(s.index);else{const e=r.addLocal("v128");r.localGet(s.index).localSet(e),r.localGet(s.index),i(),r[a](),this.vSetLocal(s.index),r.localGet(e)}return s.wtype}vstmtIf(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementBody(e.consequent),e.alternate&&(t.else_(),this.vstatementBody(e.alternate)),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.consequent),this.vMaskDepth--,this.exit(),e.alternate&&(t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),t.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vMaskDepth++,this.vstatementBody(e.alternate),this.vMaskDepth--,this.exit()),this.vRecomputeCur(r)}vstmtReturn(e){const t=this.em;if(!e.argument)return void this.vRetireOrReturn();this.pushState("skip-literal-correction");const s=this.getType(e.argument);switch(this.popState("skip-literal-correction"),this.returnType){case"Array(2)":case"Array(3)":case"Array(4)":{const s=parseInt(this.returnType.substring(6),10),r=e.argument,n=[];if("ArrayExpression"===r.type){if(r.elements.length!==s)throw this.astErrorOutput(`expected ${s} array elements to match return type ${this.returnType}`,e);for(let e=0;e0?i=this.vCur:-1!==this.vRetMask&&(i=t.addLocal("v128"),t.localGet(this.vRetMask).v128Not().localSet(i));const a=t.addLocal("i32");if(1===n)return t.globalGet(s.dataIndex).i32Const(2).i32Shl().localSet(a),void(-1===i?t.localGet(a).localGet(e[0]).v128Store(r,2):(t.localGet(a),t.localGet(e[0]),t.localGet(a).v128Load(r,2),t.localGet(i).v128Bitselect(),t.v128Store(r,2)));t.globalGet(s.dataIndex).i32Const(n).i32Mul().i32Const(2).i32Shl().localSet(a);for(let s=0;s<4;s++)for(let o=0;oe.test&&this.vInfo.exprVarying(e.test)),i=this.getType(t);if(!n){let n,a;switch(i){case"Float":case"Number":a=!1,n=r.addLocal("f32"),this.coerce(this.expression(t),"f32"),r.localSet(n);break;case"Integer":a=!0,n=r.addLocal("i32"),this.coerce(this.expression(t),"i32"),r.localSet(n);break;default:throw this.astErrorOutput(`Unhandled switch discriminant type "${i}"`,e)}if(1===s.length&&!s[0].test)return void this.vEmitSwitchConsequent(s[0].consequent);const{groups:o,defaultConsequent:u}=this.collectSwitchGroups(s),l=e=>{if(e===o.length)return void(u&&this.vEmitSwitchConsequent(u));const{tests:t,consequent:s}=o[e];for(let e=0;e0&&r.i32Or();this.enterIf(),this.vEmitSwitchConsequent(s),(e+10&&r.v128Or();r.localSet(p),this.vRecomputeCur(h),r.localGet(this.vCur).localGet(p).v128And().localGet(c).v128Andnot().localSet(this.vCur),r.localGet(c).localGet(p).v128Or().localSet(c),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(s),this.exit()}l&&(this.vRecomputeCur(h),r.localGet(this.vCur).localGet(c).v128Andnot().localSet(this.vCur),r.localGet(this.vCur).v128AnyTrue(),this.enterIf(),this.vEmitSwitchConsequent(l),this.exit()),this.vMaskDepth--,this.vRecomputeCur(h)}vEmitSwitchTest(e,t){const s=this.getType(e);t?"Number"===s||"Float"===s?this.vCastValueToInteger(e):"LiteralInteger"===s?this.vCastLiteralToInteger(e):this.vCoerce(this.vexpr(e),"vi32"):"LiteralInteger"===s?this.vCastLiteralToFloat(e):"Integer"===s?this.vCastValueToFloat(e):this.vCoerce(this.vexpr(e),"vf32")}vEmitSwitchConsequent(e){const t=this.collectSwitchCaseStatements(e),s=this.vTerminated;this.vTerminated=!1;for(let e=0;e{const s=this.getType(t);switch(n){case"Number":case"Float":"Integer"===s?this.vCastValueToFloat(t):"LiteralInteger"===s?this.vCastLiteralToFloat(t):this.vCoerce(this.vexpr(t),"vf32");break;case"Integer":"Number"===s||"Float"===s?this.vCastValueToInteger(t):"LiteralInteger"===s?this.vCastLiteralToInteger(t):this.vCoerce(this.vexpr(t),"vi32");break;case"Boolean":this.vexprMask(t);break;default:throw this.astErrorOutput(`WebAssembly backend does not yet support a ternary of type ${n}`,e)}},a="Integer"===n?"vi32":"Boolean"===n?"vbool":"vf32";if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf("v128"),i(e.consequent),t.else_(),i(e.alternate),this.exit(),a;const o=t.addLocal("v128");this.vexprMask(e.test),t.localSet(o);const u=t.addLocal("v128");t.localGet(this.vCur).localSet(u);const l=t.addLocal("v128"),h=t.addLocal("v128");return t.localGet(u).localGet(o).v128And().localSet(this.vCur),this.vMaskDepth++,i(e.consequent),t.localSet(l),t.localGet(u).localGet(o).v128Andnot().localSet(this.vCur),i(e.alternate),t.localSet(h),this.vMaskDepth--,t.localGet(u).localSet(this.vCur),t.localGet(l).localGet(h).localGet(o).v128Bitselect(),a}vTernaryStatement(e){const t=this.em;if(!this.vInfo.exprVarying(e.test))return this.emitCondition(e.test),this.enterIf(),this.vstatementExpression(e.consequent),t.else_(),this.vstatementExpression(e.alternate),void this.exit();const s=t.addLocal("v128");this.vexprMask(e.test),t.localSet(s);const r=t.addLocal("v128");t.localGet(this.vCur).localSet(r),t.localGet(r).localGet(s).v128And().localSet(this.vCur),this.vMaskDepth++,this.vstatementExpression(e.consequent),t.localGet(r).localGet(s).v128Andnot().localSet(this.vCur),this.vstatementExpression(e.alternate),this.vMaskDepth--,t.localGet(r).localSet(this.vCur)}vexprCall(e){if(!e.callee)throw this.astErrorOutput("Unknown CallExpression",e);if("MemberExpression"===e.callee.type&&"this.color"===this.getVariableSignature(e.callee,!0))throw this.astErrorOutput("WebAssembly backend does not yet support graphical mode (this.color)",e);let t=null;const s=this.isAstMathFunction(e);if(t=s||e.callee.object&&"ThisExpression"===e.callee.object.type?e.callee.property.name:"SequenceExpression"!==e.callee.type||"Literal"!==e.callee.expressions[0].type||isNaN(e.callee.expressions[0].raw)?e.callee.name:e.callee.expressions[1].property.name,!t)throw this.astErrorOutput("Unhandled function, couldn't find name",e);return s?this.vMathCall(t,e):this.vUserCall(t,e)}vUserCall(e,t){const s=this.em,r=this.assembler.helperInfo||{readsThread:!1,usesRandom:!1},n=this.assembler.globals,i=this.getType(t),a=this.lookupFunctionArgumentTypes(e)||[],o=[];for(let r=0;r0&&s.i32Const(t).i32Add(),s.globalSet(n.threadX)),r.usesRandom&&s.localGet(c).i32x4ExtractLane(t).globalSet(n.pcgState);for(const e of o)s.localGet(e.index),"vi32"===e.wtype?s.i32x4ExtractLane(t):s.f32x4ExtractLane(t);s.call(this.mangleFunctionName(e)),"void"!==u&&s.localSet(l),r.usesRandom&&s.localGet(c).globalGet(n.pcgState).i32x4ReplaceLane(t).localSet(c),"void"!==u&&(0===t?(s.localGet(l),"i32"===u?s.i32x4Splat():s.f32x4Splat(),s.localSet(h)):(s.localGet(h).localGet(l),"i32"===u?s.i32x4ReplaceLane(t):s.f32x4ReplaceLane(t),s.localSet(h)))}return r.readsThread&&s.localGet(this._vBaseX).globalSet(n.threadX),r.usesRandom&&(s.localGet(c).globalGet(n.pcgStateV),this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.v128Bitselect().globalSet(n.pcgStateV)),"void"===u?"void":(s.localGet(h),"i32"===u?"vi32":"vf32")}vMathCall(e,t){const s=this.em;if("random"===e)return this.usesRandom=!0,this.vMaskDepth>0?s.localGet(this.vCur):s.v128ConstI32x4(-1,-1,-1,-1),s.call("pcg_random_v"),"vf32";const r=e=>{switch(this.getType(e)){case"Integer":this.vCastValueToFloat(e);break;case"LiteralInteger":this.vCastLiteralToFloat(e);break;default:this.vCoerce(this.vexpr(e),"vf32")}},n=v[e];if(n)return r(t.arguments[0]),s[n](),"vf32";switch(e){case"round":return r(t.arguments[0]),s.v128ConstF32x4(.5,.5,.5,.5).f32x4Add().f32x4Floor(),"vf32";case"fround":return r(t.arguments[0]),"vf32";case"min":case"max":{const n="min"===e?"f32x4Min":"f32x4Max";r(t.arguments[0]);for(let e=1;e{s.localGet(e.indices[t]),"vec"===e.kind&&s.f32x4Splat()};if("Literal"===t.type&&Number.isInteger(t.value)){if(t.value<0||t.value>=e.n)throw this.astErrorOutput(`index ${t.value} out of range for Array(${e.n})`,t);return r(t.value),"vf32"}const n=s.addLocal("v128");this.vEmitIndex(t),s.localSet(n);const i=s.addLocal("v128");r(0),s.localSet(i);for(let t=1;tthis.isThreadDependent(e));switch(e.type){case"MemberExpression":{const t=this.getVariableSignature(e);if("this.thread.value"===t||"value.thread.value"===t)return"x"===e.property.name;break}case"CallExpression":if(this.isAstMathFunction(e)){if("random"===e.callee.property.name)return!0;break}return!0;case"Identifier":return!!this.taintedLocals&&this.taintedLocals.has(e.name);case"ThisExpression":return!1}for(const t in e){if("loc"===t||"start"===t||"end"===t||"parent"===t)continue;const s=e[t];if(s&&"object"==typeof s&&this.isThreadDependent(s))return!0}return!1}recordUniformity(e,t){this._analysisPass&&this.uniformity.push({kind:e,threadDependent:!t||this.isThreadDependent(t)})}}}}),ut=e((e,t)=>{let s=null;try{s=d()}catch(e){}const r="function"==typeof Worker;const n="\nvar entries = {};\nvar pipelines = {};\nfunction handleMessage(message, post) {\n if (message.type === 'setup') {\n var imports = { env: { memory: message.memory } };\n for (var i = 0; i < message.mathImports.length; i++) {\n imports.env['math_' + message.mathImports[i]] = Math[message.mathImports[i]];\n }\n var instance = new WebAssembly.Instance(message.module, imports);\n entries[message.id] = {\n run: instance.exports.run,\n runSimd: instance.exports.run_simd || null,\n sizeX: message.sizeX\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'pipelineSetup') {\n var instances = [];\n for (var i = 0; i < message.modules.length; i++) {\n var imports = { env: { memory: message.memory } };\n var math = message.moduleMathImports[i];\n for (var j = 0; j < math.length; j++) {\n imports.env['math_' + math[j]] = Math[math[j]];\n }\n instances.push(new WebAssembly.Instance(message.modules[i], imports));\n }\n var steps = [];\n for (var i = 0; i < message.steps.length; i++) {\n var exported = instances[message.steps[i].module].exports;\n steps.push({\n run: exported.run,\n runSimd: exported.run_simd || null,\n sizeX: message.steps[i].sizeX\n });\n }\n pipelines[message.id] = {\n steps: steps,\n i32: new Int32Array(message.memory.buffer),\n countIndex: message.countIndex,\n genIndex: message.genIndex,\n abortIndex: message.abortIndex\n };\n post({ type: 'ready', id: message.id });\n } else if (message.type === 'release') {\n delete entries[message.id];\n delete pipelines[message.id];\n } else if (message.type === 'run') {\n var entry = entries[message.id];\n var start = message.start;\n var end = message.end;\n var seed = message.seed;\n if (entry.runSimd && (entry.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) entry.runSimd(start, quadEnd, seed);\n if (quadEnd < end) entry.run(quadEnd, end, seed);\n } else {\n entry.run(start, end, seed);\n }\n post({ type: 'done', taskId: message.taskId });\n } else if (message.type === 'pipelineRun') {\n var pipeline = pipelines[message.id];\n var i32 = pipeline.i32;\n var gen = message.baseGen;\n var aborted = false;\n for (var s = 0; s < pipeline.steps.length && !aborted; s++) {\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n var step = pipeline.steps[s];\n var start = message.ranges[s * 2];\n var end = message.ranges[s * 2 + 1];\n var seed = message.seeds[s];\n if (end > start) {\n if (step.runSimd && (step.sizeX & 3) === 0 && (start & 3) === 0) {\n var quadEnd = end - ((end - start) & 3);\n if (quadEnd > start) step.runSimd(start, quadEnd, seed);\n if (quadEnd < end) step.run(quadEnd, end, seed);\n } else {\n step.run(start, end, seed);\n }\n }\n gen++;\n if (Atomics.add(i32, pipeline.countIndex, 1) + 1 === message.workerCount) {\n Atomics.store(i32, pipeline.countIndex, 0);\n Atomics.store(i32, pipeline.genIndex, gen);\n Atomics.notify(i32, pipeline.genIndex);\n } else {\n for (;;) {\n if (Atomics.load(i32, pipeline.genIndex) >= gen) break;\n if (Atomics.load(i32, pipeline.abortIndex)) {\n aborted = true;\n break;\n }\n Atomics.wait(i32, pipeline.genIndex, gen - 1, 100);\n }\n }\n }\n post({ type: 'done', taskId: message.taskId, aborted: aborted });\n }\n}\nif (typeof self !== 'undefined' && typeof postMessage === 'function') {\n self.onmessage = function(event) {\n handleMessage(event.data, function(message) { postMessage(message); });\n };\n} else {\n var parentPort = require('worker_threads').parentPort;\n parentPort.on('message', function(message) {\n handleMessage(message, function(reply) { parentPort.postMessage(reply); });\n });\n}\n";t.exports={WebAssemblyWorkerPool:class{constructor(e){this.size=e||function(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;if(s&&"function"==typeof s.cpus){const e=s.cpus().length;if(e)return e}return 4}(),this.workers=[],this.destroyed=!1,this.dispatchCount=0,this.lastDispatch=null,this._taskId=0}get liveWorkerCount(){let e=0;for(const t of this.workers)t.dead||e++;return e}_spawn(){const e={handle:null,dead:!1,state:{setup:new Set,settingUp:new Map,pending:new Map},fail:null,die:null},t=e.state;e.fail=e=>{for(const s of t.settingUp.values())s.reject(e);t.settingUp.clear();for(const s of t.pending.values())s.reject(e);t.pending.clear()},e.die=t=>{if(!e.dead&&(e.dead=!0,e.fail(t),e.handle&&"function"==typeof e.handle.terminate))try{e.handle.terminate()}catch(e){}};const s=s=>{if("ready"===s.type){const r=t.settingUp.get(s.id);r&&(t.settingUp.delete(s.id),t.setup.add(s.id),this._updateRef(e),r.resolve())}else if("done"===s.type){const r=t.pending.get(s.taskId);r&&(t.pending.delete(s.taskId),this._updateRef(e),r.resolve())}};let i;if(r){const t=URL.createObjectURL(new Blob([n],{type:"text/javascript"}));i=new Worker(t),URL.revokeObjectURL(t),i.onmessage=e=>s(e.data),i.onerror=t=>e.die(new Error(t.message||"WebAssembly worker error"))}else{const{Worker:t}=d();i=new t(n,{eval:!0}),i.on("message",s),i.on("error",t=>e.die(t)),i.on("exit",t=>{e.die(new Error(`WebAssembly worker exited with code ${t}`))}),i.unref()}return e.handle=i,e}_worker(e){for(;this.workers.length<=e;)this.workers.push(this._spawn());return this.workers[e].dead&&(this.workers[e]=this._spawn()),this.workers[e]}_updateRef(e){!e.dead&&e.handle&&"function"==typeof e.handle.ref&&(e.state.settingUp.size+e.state.pending.size>0?e.handle.ref():e.handle.unref())}_ensureSetup(e,t){if(e.state.setup.has(t.id))return Promise.resolve();let s=e.state.settingUp.get(t.id);return s||(s={},s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),e.state.settingUp.set(t.id,s),this._updateRef(e),e.handle.postMessage(t.pipeline?{type:"pipelineSetup",id:t.id,memory:t.memory,modules:t.modules,moduleMathImports:t.moduleMathImports,steps:t.steps,countIndex:t.countIndex,genIndex:t.genIndex,abortIndex:t.abortIndex}:{type:"setup",id:t.id,module:t.module,memory:t.memory,mathImports:t.mathImports,sizeX:t.sizeX})),s.promise}dispatch(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:t.length,ranges:t.map(e=>[e.start,e.end])};const s=t.map((t,s)=>{const r=this._worker(s);return this._ensureSetup(r,e).then(()=>new Promise((s,n)=>{if(r.dead)return void n(new Error("WebAssembly worker died before the task could run"));const i=++this._taskId;r.state.pending.set(i,{resolve:s,reject:n}),this._updateRef(r),r.handle.postMessage({type:"run",id:e.id,taskId:i,start:t.start,end:t.end,seed:t.seed})}))});return Promise.all(s).then(()=>{})}dispatchPipeline(e,t){if(this.destroyed)return Promise.reject(new Error("WebAssembly worker pool has been destroyed"));this.dispatchCount++,this.lastDispatch={workerCount:e.workerCount,ranges:e.workerRanges.map(e=>e.slice())};const s=[];for(let r=0;rnew Promise((s,i)=>{if(n.dead)return void i(new Error("WebAssembly worker died before the task could run"));const a=++this._taskId;n.state.pending.set(a,{resolve:s,reject:i}),this._updateRef(n),n.handle.postMessage({type:"pipelineRun",id:e.id,taskId:a,ranges:e.workerRanges[r],seeds:t.seeds,baseGen:t.baseGen,workerCount:e.workerCount})})))}return Promise.all(s).then(()=>{})}release(e){if(!this.destroyed)for(const t of this.workers){if(t.dead)continue;t.state.setup.delete(e);const s=t.state.settingUp.get(e);s&&(t.state.settingUp.delete(e),s.reject(new Error("WebAssembly kernel entry released during setup")),this._updateRef(t)),t.handle.postMessage({type:"release",id:e})}}destroy(){if(this.destroyed)return;this.destroyed=!0;const e=new Error("WebAssembly worker pool has been destroyed");for(const t of this.workers)t.dead=!0,t.fail(e),t.handle.terminate();this.workers=[]}}}}),lt=e((e,t)=>{const{Kernel:s}=a(),{FunctionBuilder:n}=o(),{WebAssemblyFunctionNode:u}=ot(),{WasmModuleBuilder:l}=at(),{WebAssemblyWorkerPool:h}=ut(),{utils:c}=i(),{Input:p}=r(),d=Object.freeze({kernelMap:!1,isIntegerDivisionAccurate:!0,isSpeedTacticSupported:!1,isTextureFloat:!0,isDrawBuffers:!1,kernelMapSize:0,channelCount:1,maxTextureSize:1/0,isFloatRead:!0});let f=null,m=null,g=1;t.exports={WebAssemblyKernel:class e extends s{static get isSupported(){return"object"==typeof WebAssembly&&null!==WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0]))}static get isSIMDSupported(){if(null===f)try{const e=new l;e.addFunction("t",{params:[],results:[]}).v128ConstI32x4(0,0,0,0).drop(),f=WebAssembly.validate(e.toBytes())}catch(e){f=!1}return f}static get isThreadsSupported(){if(null===m)try{if("undefined"==typeof SharedArrayBuffer)m=!1;else{const e=new l;e.addMemoryImport(1,1,!0);const t=new WebAssembly.Memory({initial:1,maximum:1,shared:!0});new WebAssembly.Instance(new WebAssembly.Module(e.toBytes()),{env:{memory:t}}),m=!0}}catch(e){m=!1}return m}static isContextMatch(e){return!1}static getFeatures(){return d}static get features(){return d}static get mode(){return"webasm"}static getSignature(e,t){return"webasm"+(t.length>0?":"+t.join(","):"")}static destroyContext(e){}static dispatchSpans(e,t,s,r,n){if(!t||0===s)return e(0,s,n),"scalar";if(!(3&r))return t(0,s,n),"simd";const i=-4&r,a=s/r;for(let s=0;s0&&t(a,a+i,n),e(a+i,a+r,n)}return i>0?"simd+scalar-tail":"scalar"}static nativeFunctionArguments(){throw new Error("WebAssembly backend does not yet support native functions")}static nativeFunctionReturnType(){throw new Error("WebAssembly backend does not yet support native functions")}static combineKernels(){throw new Error("WebAssembly backend does not yet support combineKernels")}constructor(e,t){super(e,t),this.poolSize=null,this.mergeSettings(e.settings||t),null===this.precision&&(this.precision="single"),this.threadDim=null,this.componentCount=1,this.moduleCacheLimit=8,this.functionBuilder=null,this.tracedFunctions=null,this.usesRandom=!1,this.usedMathImports=null,this._moduleCache=new Map,this._active=null,this._lastRunPath=null,this._pool=null,this._threadedTail=Promise.resolve(),this._threadedBusy=0,this._threadedEpoch=0}initCanvas(){return this.graphical&&"undefined"!=typeof document?document.createElement("canvas"):null}initContext(){return null}initPlugins(e){return[]}setOutput(e){const t=this.toKernelOutput(e);if(this.built&&!this.dynamicOutput)throw new Error("Resizing a kernel with dynamicOutput: false is not possible");return this.output=t,this}toString(){throw new Error("WebAssembly backend does not yet support toString")}build(){if(this.built)return;if(this.gpu&&this.gpu.kernels&&-1===this.gpu.kernels.indexOf(this)&&this.gpu.kernels.push(this),this.graphical)return this.requestFallback(arguments,"graphical mode is not supported on the webasm backend");if(this.subKernels&&this.subKernels.length>0)return this.requestFallback(arguments,"kernel maps are not supported on the webasm backend");this.setupConstants(),this.setupArguments(arguments);for(let e=0;e16*Math.ceil(e/16);let s=0;const r={},n={};for(let i=0;i=4096}_entryKey(e){return this._computeSizeSignature(e)+(this._threadable()?"|shared":"")}_assembleModule(t,s,r){const n=new l,i=t.totalBytes||t.outputOffset+s*this.componentCount*4,a=Math.ceil(i/65536)+16,o=Math.max(a,4096);n.addMemoryImport(a,o,r);const u=Array.from(this.usedMathImports).sort();for(const e of u){const t="pow"===e||"atan2"===e?["f32","f32"]:["f32"];n.addFuncImport("math_"+e,t,["f32"])}const h={threadX:n.addGlobal("i32",!0,0),threadY:n.addGlobal("i32",!0,0),threadZ:n.addGlobal("i32",!0,0),dataIndex:n.addGlobal("i32",!0,0)};this.usesRandom&&(h.pcgState=n.addGlobal("i32",!0,0),this._emitPcgRandom(n,h.pcgState));const c={module:n,layout:t,globals:h};for(let e=this.tracedFunctions.length-1;e>=0;e--){const t=this.tracedFunctions[e];if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(s.output=this.output,s.emitFunction(c))}this.functionBuilder.functionMap.kernel.output=this.output,this.functionBuilder.functionMap.kernel.emitFunction(c);const[p,d]=this.threadDim,f=n.addFunction("run",{params:["i32","i32","i32"],locals:["i32"]});if(f.localGet(0).localSet(3),1===this.output.length?(f.i32Const(0).globalSet(h.threadY),f.i32Const(0).globalSet(h.threadZ)):2===this.output.length&&f.i32Const(0).globalSet(h.threadZ),f.block(),f.localGet(3).localGet(1).i32GeS().brIf(0),f.loop(),f.localGet(3).globalSet(h.dataIndex),1===this.output.length?f.localGet(3).globalSet(h.threadX):2===this.output.length?(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().globalSet(h.threadY)):(f.localGet(3).i32Const(p).i32RemU().globalSet(h.threadX),f.localGet(3).i32Const(p).i32DivU().i32Const(d).i32RemU().globalSet(h.threadY),f.localGet(3).i32Const(p*d).i32DivU().globalSet(h.threadZ)),this.usesRandom&&f.localGet(2).localGet(3).i32Const(-1640531527).i32Mul().i32Add().i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(h.pcgState),f.call("kernel"),f.localGet(3).i32Const(1).i32Add().localSet(3),f.localGet(3).localGet(1).i32LtS().brIf(0),f.end(),f.end(),n.exportFunction("run"),e.isSIMDSupported){this.usesRandom&&(h.pcgStateV=n.addGlobal("v128",!0,0),this._emitPcgRandomVector(n,h.pcgStateV));let e=null;for(const t of this.tracedFunctions){if("kernel"===t)continue;const s=this.functionBuilder.functionMap[t];s&&(e||(e={readsThread:!1,usesRandom:!1}),s.readsThread&&(e.readsThread=!0),s.usesRandom&&(e.usesRandom=!0))}c.helperInfo=e,this.functionBuilder.functionMap.kernel.emitVectorFunction(c),this._emitRunSimd(n,h),n.exportFunction("run_simd")}return{bytes:n.toBytes(),initial:a,maximum:o}}_emitRunSimd(e,t){const[s,r]=this.threadDim,n=e.addFunction("run_simd",{params:["i32","i32","i32"],locals:["i32"]});n.localGet(0).localSet(3),1===this.output.length?(n.i32Const(0).globalSet(t.threadY),n.i32Const(0).globalSet(t.threadZ)):2===this.output.length&&n.i32Const(0).globalSet(t.threadZ),n.block(),n.localGet(3).localGet(1).i32GeS().brIf(0),n.loop(),n.localGet(3).globalSet(t.dataIndex),1===this.output.length?n.localGet(3).globalSet(t.threadX):2===this.output.length?(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().globalSet(t.threadY)):(n.localGet(3).i32Const(s).i32RemU().globalSet(t.threadX),n.localGet(3).i32Const(s).i32DivU().i32Const(r).i32RemU().globalSet(t.threadY),n.localGet(3).i32Const(s*r).i32DivU().globalSet(t.threadZ)),this.usesRandom&&(n.localGet(3).i32x4Splat().v128ConstI32x4(0,1,2,3).i32x4Add(),n.v128ConstI32x4(-1640531527,-1640531527,-1640531527,-1640531527).i32x4Mul(),n.localGet(2).i32x4Splat().i32x4Add(),n.v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul(),n.v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add(),n.globalSet(t.pcgStateV)),n.call("kernel_simd"),n.localGet(3).i32Const(4).i32Add().localSet(3),n.localGet(3).localGet(1).i32LtS().brIf(0),n.end(),n.end()}_emitPcgRandomVector(e,t){const s=e.addFunction("pcg_random_v",{params:["v128"],results:["v128"]}),r=s.addLocal("v128"),n=s.addLocal("i32");s.globalGet(t).v128ConstI32x4(747796405,747796405,747796405,747796405).i32x4Mul().v128ConstI32x4(-1403630843,-1403630843,-1403630843,-1403630843).i32x4Add().globalGet(t).localGet(0).v128Bitselect().globalSet(t),s.globalGet(t).localSet(r),s.localGet(r).i32x4ExtractLane(0).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4Splat();for(let e=1;e<4;e++)s.localGet(r).i32x4ExtractLane(e).localSet(n),s.localGet(n).localGet(n).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().i32x4ReplaceLane(e);s.localGet(r).v128Xor(),s.v128ConstI32x4(277803737,277803737,277803737,277803737).i32x4Mul();const i=s.addLocal("v128");s.localTee(i),s.i32Const(22).i32x4ShrU().localGet(i).v128Xor(),s.i32Const(8).i32x4ShrU(),s.f32x4ConvertI32x4U(),s.v128ConstF32x4(16777216,16777216,16777216,16777216).f32x4Div()}_emitPcgRandom(e,t){const s=e.addFunction("pcg_random",{params:[],results:["f32"]}),r=s.addLocal("i32");s.globalGet(t).i32Const(747796405).i32Mul().i32Const(-1403630843).i32Add().globalSet(t),s.globalGet(t).globalGet(t).i32Const(28).i32ShrU().i32Const(4).i32Add().i32ShrU().globalGet(t).i32Xor().i32Const(277803737).i32Mul().localTee(r),s.i32Const(22).i32ShrU().localGet(r).i32Xor().i32Const(8).i32ShrU().f32ConvertI32U().f32Const(16777216).f32Div()}_releaseEntry(e){const t=()=>{e.instance=null,e.module=null,e.memory=null,e.run=null,e.runSimd=null,e.f32=null,e.i32=null,e.bytes=null};if(e.shared&&this._pool){const s=this._pool;this._threadedTail.then(()=>{s.release(e.id),t()},t)}else t()}_instantiate(e,t){let s=this._moduleCache.get(e);if(s&&(this._moduleCache.delete(e),this._moduleCache.set(e,s)),!s){const r=this._threadable(),n=this.computeLayout(t),[i,a,o]=this.threadDim,u=i*a*o,{bytes:l,initial:h,maximum:d}=this._assembleModule(n,u,r);if(!WebAssembly.validate(l))throw new Error("WebAssembly backend: generated module failed validation (internal error)");const f=r?new WebAssembly.Memory({initial:h,maximum:d,shared:!0}):new WebAssembly.Memory({initial:h,maximum:d}),m={env:{memory:f}};for(const e of this.usedMathImports)m.env["math_"+e]=Math[e];const y=new WebAssembly.Module(l),x=new WebAssembly.Instance(y,m);s={id:g++,sizeSignature:e,shared:r,layout:n,cells:u,bytes:l,module:y,memory:f,mathImports:Array.from(this.usedMathImports).sort(),sizeX:i,instance:x,run:x.exports.run,runSimd:x.exports.run_simd||null,f32:new Float32Array(f.buffer),i32:new Int32Array(f.buffer)};for(const e in n.constantArrays){const t=n.constantArrays[e],r=this.constants[e];c.flattenTo(r instanceof p?r.value:r,s.f32.subarray(t.offset/4,t.offset/4+t.flatLength))}for(this._moduleCache.set(e,s);this._moduleCache.size>Math.max(this.moduleCacheLimit,1);){const e=this._moduleCache.keys().next().value,t=this._moduleCache.get(e);this._moduleCache.delete(e),this._releaseEntry(t)}}this._active=s}checkArgumentTypes(e){if(super.checkArgumentTypes(e),!this.argumentTypes)return;const t=Math.min(e.length,this.argumentTypes.length);for(let s=0;s>>0:4294967296*Math.random()>>>0),l|=0,this._lastRunPath=e.dispatchSpans(o,u,n,t[0],l);const h=r.outputOffset/4,d=i.slice(h,h+n*this.componentCount);return this._shapeOutput(d,Array.from(this.output),this.componentCount)}_runThreaded(e){const t=this._active,{layout:s,cells:r}=t,n=0===this._threadedBusy;let i=null,a=null;if(n){for(const r in s.arrays){const n=s.arrays[r],i=e[n.index];c.flattenTo(i instanceof p?i.value:i,t.f32.subarray(n.offset/4,n.offset/4+n.flatLength))}for(const r in s.scalars){const n=s.scalars[r],i=e[n.index];"Integer"===n.type?t.i32[n.offset/4]=0|i:"Boolean"===n.type?t.i32[n.offset/4]=i?1:0:t.f32[n.offset/4]=i}}else{i=[];for(const t in s.arrays){const r=s.arrays[t],n=e[r.index],a=new Float32Array(r.flatLength);c.flattenTo(n instanceof p?n.value:n,a),i.push({record:r,flat:a})}a=[];for(const t in s.scalars){const r=s.scalars[t];a.push({record:r,value:e[r.index]})}}let o=0;this.usesRandom&&(o=null!==this.randomSeed?this.randomSeed>>>0:4294967296*Math.random()>>>0),o|=0,this._pool||(this._pool=new h(this.poolSize||void 0));const u=this._pool,l=this.componentCount,d=Array.from(this.output);this._threadedBusy++;const f=this._threadedTail.then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");if(i){for(let e=0;e=r)break;h.push({start:s,end:t===e-1?r:Math.min(s+n,r),seed:o})}return this._lastRunPath="threaded",u.dispatch(t,h).then(()=>{if(!t.f32)throw new Error("WebAssembly kernel was destroyed");const e=s.outputOffset/4,n=t.f32.slice(e,e+r*l);return this._shapeOutput(n,d,l)})}),m=this._threadedEpoch,g=()=>{this._threadedEpoch===m&&this._threadedBusy--};return this._threadedTail=f.then(g,g),f}_shapeOutput(e,t,s){const[r,n,i]=[t[0],t[1]||1,t[2]||1];if(1===s)switch(t.length){case 1:return c.erectMemoryOptimizedFloat(e,r);case 2:return c.erectMemoryOptimized2DFloat(e,r,n);default:return c.erectMemoryOptimized3DFloat(e,r,n,i)}const a=s,o=t=>{const s=new Array(r);for(let n=0;n{const{utils:s}=i(),{Input:n}=r(),{WebAssemblyKernel:a}=lt(),{WebAssemblyWorkerPool:o}=ut(),u=["Array","Input","Number","Float","Integer","Boolean"];let l=1;var h=class extends Error{constructor(e,t){super(e),this.isFusionFallback=!0,this.recompilable=Boolean(t)}};function c(e){return e&&"function"==typeof e.toArray?e.toArray():e}function p(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function d(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}t.exports={WebAssemblyPipelineExecutor:class e{static compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let d=r.get(p);if(!d){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(o.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=o.clone.kernel;this._prepareKernel(e,l),d={id:r.size,kernel:e,constantRegions:null},r.set(p,d)}u[n]=d,c[n]=l}for(let e=0;e{const t=p;return p=(e=>16*Math.ceil(e/16))(p+e),t};let f=0,m=-1;if(!this.pipeline._threadsDisabled&&a.isThreadsSupported){let e=0;for(let s=0;se&&(e=n)}const s=new o;f=Math.min(s.size,Math.ceil(e/4096)),f>1?(this.threaded=!0,this.kind="fused-threaded",this.pool=s,m=d(12)):s.destroy()}const g=new Map,y=new Map,x=new Map,b=[],v=[],S=[],T=new Array(t.steps.length);for(let e=0;e${i}`;let l=E.get(o);if(!l){const a={arrays:n.arrays,scalars:n.scalars,constantArrays:s.constantRegions,outputOffset:i,totalBytes:_},u=w[t.steps[e].outputBuffer].cells,h=r._assembleModule(a,u,this.threaded);null===this.memory&&(this.memory=this.threaded?new WebAssembly.Memory({initial:h.initial,maximum:h.maximum,shared:!0}):new WebAssembly.Memory({initial:h.initial,maximum:h.maximum}),this.f32=new Float32Array(this.memory.buffer),this.i32=new Int32Array(this.memory.buffer));const c={env:{memory:this.memory}};for(const e of r.usedMathImports)c.env["math_"+e]=Math[e];const p=new WebAssembly.Module(h.bytes),d=new WebAssembly.Instance(p,c);l={run:d.exports.run,runSimd:d.exports.run_simd||null,moduleIndex:k.length},k.push(p),C.push(Array.from(r.usedMathImports).sort()),E.set(o,l)}I[e]={run:l.run,runSimd:l.runSimd,moduleIndex:l.moduleIndex,cells:w[t.steps[e].outputBuffer].cells,sizeX:r.threadDim[0],usesRandom:r.usesRandom,randomSeed:r.randomSeed}}if(this.threaded){const e=[];for(let s=0;s=t?(r[2*e]=0,r[2*e+1]=0):(r[2*e]=i,r[2*e+1]=s===f-1?t:Math.min(i+n,t))}e.push(r)}this._entry={id:"pipeline:"+l++,pipeline:!0,memory:this.memory,modules:k,moduleMathImports:C,steps:I.map(e=>({module:e.moduleIndex,sizeX:e.sizeX})),countIndex:m/4,genIndex:m/4+1,abortIndex:m/4+2,workerCount:f,workerRanges:e}}for(let e=0;e{const s=e.binding;if("step"===s.source){const e=s.step,r=w[t.steps[e].outputBuffer],n=u[e].kernel;return{kind:"step",base:r.offset/4,count:r.cells*n.componentCount,output:t.steps[e].output,componentCount:n.componentCount,kernel:n}}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),this._stepRuns=I,this._argArrayRegions=g,this._argScalarSlots=y,this._scratch=null}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0:4294967296*Math.random()>>>0):0}_executeThreaded(e){const t=this._entry,s=this.i32,r=this._stepRuns.map(e=>this._drawSeed(e));this._lastRunAborted&&(Atomics.store(s,t.countIndex,0),Atomics.store(s,t.abortIndex,0),this._lastRunAborted=!1,this._abortError=null);const n=Atomics.load(s,t.genIndex),i=n+this._stepRuns.length;return this.pool.dispatchPipeline(t,{baseGen:n,seeds:r}).then(null,e=>this._abort(e)),this._waitForGeneration(i).then(()=>this._readResults(e))}_waitForGeneration(e){const t=this.i32,s=this._entry.genIndex,r="function"==typeof Atomics.waitAsync?Atomics.waitAsync:null;return new Promise((n,i)=>{const a="function"==typeof setInterval?setInterval(()=>{},200):null,o=(e,t)=>{null!==a&&clearInterval(a),e(t)},u=this._entry.countIndex;let l=Atomics.load(t,s),h=Atomics.load(t,u),c=Date.now();const p=()=>{if(this._abortError)return void o(i,this._abortError);const a=Atomics.load(t,s);if(a>=e)return void o(n);const d=Atomics.load(t,u);if(a!==l||d!==h)l=a,h=d,c=Date.now();else if(Date.now()-c>=this.sanityTimeoutMs){const t=new Error(`pipeline threaded barrier stalled at generation ${a} of ${e} for ${this.sanityTimeoutMs}ms`);return this._abort(t),void o(i,t)}if(r){const e=Math.max(1,Math.min(200,this.sanityTimeoutMs)),n=r(t,s,a,e);n.async?n.value.then(p):Promise.resolve().then(p)}else setTimeout(p,1)};p()})}_abort(e){if(!this._abortError&&(this._abortError=e||new Error("pipeline threaded run aborted"),this._lastRunAborted=!0,this.i32&&this._entry&&(Atomics.store(this.i32,this._entry.abortIndex,1),Atomics.notify(this.i32,this._entry.genIndex)),this.pool&&this.pool.workers))for(const e of this.pool.workers)!e.dead&&e.state.pending.size>0&&e.die(this._abortError)}abortRuns(e){this.threaded&&this._abort(e)}_readResults(e){const t=this.f32,s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{utils:s}=i(),{Input:n}=r(),{FusionFallback:a}=ht();function o(e){return e&&"function"==typeof e.toArray?e.toArray():e}function u(e,t,s){const r=e.limits,n=Math.min(r.maxStorageBufferBindingSize,r.maxBufferSize);if(t>n)throw new a(`${s} needs ${t} bytes but this device allows ${n} per storage buffer`)}function l(e){const t=e instanceof n?Array.from(e.size):Array.from(s.getDimensions(e));for(;t.length<3;)t.push(1);return t}function h(e,t){switch(e){case"Integer":return"number"==typeof t&&Number.isInteger(t);case"Boolean":return"boolean"==typeof t;default:return"number"==typeof t}}function c(e){return Boolean(e)&&"object"==typeof e&&!(e instanceof n)&&("function"==typeof e.toArray||"function"==typeof e.delete)}t.exports={WebGPUPipelineExecutor:class e{static async compile(t,s,r){for(let e=0;es.getVariableType(e,h)).join(",");let p=r.get(c);if(!p){let e;if(i[a.kernel]){const t=this.pipeline._cloneKernel(u.clone);this._extraShortcuts.push(t),e=t.kernel}else i[a.kernel]=!0,e=u.clone.kernel;await this._prepareKernel(e,l),p={id:r.size,kernel:e},r.set(c,p)}o[n]=p}this._scratch=null;for(let e=0;e{const s=e.output;let r=1;for(let e=0;e{let t=f.get(e);return void 0===t&&(t=f.size,f.set(e,t)),t},g=new Map;this._passes=new Array(t.steps.length);for(let r=0;r{const t=i.argBindings[e.index];return"literal"===t.source?"l"+t.value:"a"+t.index}).join(","),S=null!==f.randomSeedOffset&&null===d.randomSeed,T=c.id+":"+y.map(m).join(",")+">"+m(b)+":"+v+(S?"#"+r:"");let A=g.get(T);if(!A){const e=new ArrayBuffer(f.byteLength),t=new Uint32Array(e),s=new Int32Array(e),r=new Float32Array(e),n=d._computeDispatch(d.threadDim);t[0]=d.threadDim[0],t[1]=d.threadDim[1],t[2]=d.threadDim[2],t[3]=n.dispatchWidth;for(let e=0;e>>0);const u=h.createBuffer({size:f.byteLength,usage:72}),l=o.length>0||S;l||p.writeBuffer(u,0,e);const c=[{binding:0,resource:{buffer:u}}];for(let e=0;e{const s=e.binding;if("step"===s.source){const e=t.steps[s.step],r=this._planBuffers[e.outputBuffer],n=o[s.step].kernel,i=r.cells*n.componentCount*4,a={kind:"step",buffer:r.buffer,offset:y,byteLength:i,output:e.output,componentCount:n.componentCount,kernel:n};return y+=function(e){return 16*Math.ceil(e/16)}(i),a}return"pipelineArg"===s.source?{kind:"arg",index:s.index}:{kind:"literal",value:s.value}}),y>0&&(this._staging=h.createBuffer({size:y,usage:9}))}_representativeArgs(e,t){const s=new Array(e.argBindings.length);for(let r=0;r>>0),r.writeBuffer(s.paramsBuffer,0,s.mirror)}}const i=t.createCommandEncoder();for(let e=0;e{const t=this._staging.getMappedRange(),s=this._shapeResults(e,t);return this._staging.unmap(),s}):Promise.resolve(this._shapeResults(e,null))}_shapeResults(e,t){const s=this.plan.results,r=new Array(this._resultReads.length);for(let s=0;s{const{Input:s}=r(),{utils:n}=i(),a="pipeline intermediate results cannot be read during orchestration",o="a pipeline must return a handle, or an Array or plain object of handles",u="pipeline has been destroyed",l="the orchestration function must be synchronous; async functions and generators cannot be traced",h="this handle belongs to a different trace; handles do not survive re-trace or cross pipelines";var c=class{};let p=null;var d=class{constructor(e){this.gpu=e,this.steps=[],this.kernels=[],this.kernelIndexes=new Map,this.handleMeta=new WeakMap,this.held=[]}createHandle(e){const t=Object.freeze(new c),s=new Proxy(t,{get(e,t){if(t===Symbol.toPrimitive||"valueOf"===t||"toString"===t)return()=>{throw new Error("pipeline intermediate results cannot be used in arithmetic or conditions during orchestration")};throw new Error(a)},set(){throw new Error(a)},ownKeys(){throw new Error(a)},has(){throw new Error(a)},getOwnPropertyDescriptor(){throw new Error(a)}});return this.handleMeta.set(s,e),s}recordKernelCall(e,t){const s=e.kernel;if(s.gpu!==this.gpu)throw new Error("pipelines can only call kernels created by the same GPU instance");if(s.graphical)throw new Error("graphical kernels are not supported inside pipelines");if(s.subKernels&&s.subKernels.length>0)throw new Error("kernel maps are not supported inside pipelines");if(!s.output)throw new Error("kernels called inside a pipeline must have a fixed output size");let r=this.kernelIndexes.get(e);void 0===r&&(r=this.kernels.length,this.kernels.push(e),this.kernelIndexes.set(e,r));const n=new Array(t.length);for(let e=0;ef(e,t)):e}function m(e){for(let t=0;t{if(this.destroyed)throw new Error(u);if(this.plan||(this.plan=this._buildPlan(),this._executor=void 0),void 0===this._executor&&await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;if(this._dropExecutor(),e.recompilable){if(await this._prepareExecutor(t),this._executor)try{return await this._guardAsync(this._executor.execute(t))}catch(e){if(!e||!e.isFusionFallback)throw e;this._dropExecutor(),this._degrade(e.message)}}else this._degrade(e.message)}return this._executeGeneric(this.plan,t,r)}),i=()=>{this._inFlight--,s.length>0&&m(s)};return n.then(i,i),this._tail=n.then(b,b),n}_guardAsync(e){return e&&"function"==typeof e.then?e.then(null,e=>{throw this._dropExecutor(),e}):e}setConstants(e){this.constants=Object.assign({},e||{});const t=()=>{this._releasePlan()};return this._tail=this._tail.then(t,t),this}destroy(){if(this.destroyed=!0,this.gpu&&this.gpu.pipelines){const e=this.gpu.pipelines.indexOf(this);-1!==e&&this.gpu.pipelines.splice(e,1)}this._executor&&"function"==typeof this._executor.abortRuns&&this._executor.abortRuns(new Error(u));const e=()=>{this._releasePlan()},t=this._tail.then(e,e);return this._tail=t,t}_buildPlan(){const e=new d(this.gpu),t=new Array(this.argumentCount);for(let s=0;s({key:s,binding:e.bindValue(t)}))};if(t instanceof c)throw new Error(h);if("object"==typeof t&&!ArrayBuffer.isView(t)){if("function"==typeof t.then)throw new Error(l);const s=Object.getPrototypeOf(t);if(s!==Object.prototype&&null!==s)throw new Error(o);const r=[];for(const s in t)t.hasOwnProperty(s)&&r.push({key:s,binding:e.bindValue(t[s])});if(0===r.length)throw new Error(o);return{kind:"object",entries:r}}throw new Error(o)}(e,r),i=function(e,t){const s=new Array(e.length).fill(-1);for(let t=0;te.binding)),a=e.kernels.map(e=>({shortcut:e,clone:this._cloneKernel(e)}));return{steps:e.steps,buffers:i,results:n,kernels:a,held:e.held,genericClones:new Map}}_genericClone(e,t){const s=t.argBindings.map(e=>"step"===e.source?"T":"pipelineArg"===e.source?"a"+e.index:"l").join(","),r=t.kernel+":"+t.outputBuffer+":"+s;let n=e.genericClones.get(r);return n||(n=this._cloneKernel(e.kernels[t.kernel].clone,{immutable:!1,dynamicArguments:!1}),e.genericClones.set(r,n)),n}_prepareExecutor(e){if(this._fusionDisabled)return void(this._executor=!1);const t=this.plan.kernels;if(t.length>0&&"webgpu"===t[0].clone.kernel.constructor.mode){const{WebGPUPipelineExecutor:t}=ct();return t.compile(this,this.plan,e).then(e=>{this._executor=e,this.executorKind=e.kind,this.fallbackReason=null},e=>{this._degrade(e&&e.message||"fused executor unavailable")})}try{const{WebAssemblyPipelineExecutor:t}=ht();this._executor=t.compile(this,this.plan,e),this.executorKind=this._executor.kind,this.fallbackReason=null}catch(e){this._degrade(e&&e.message||"fused executor unavailable")}}_dropExecutor(){this._executor&&this._executor.destroy(),this._executor=void 0}_degrade(e){this._executor=!1,this.executorKind="generic",this.fallbackReason=e}_cloneKernel(e,t){const s=e.kernel,r=Object.assign({output:Array.from(s.output),pipeline:!0,immutable:!0,dynamicArguments:!0},t||{}),n=["constants","constantTypes","precision","loopMaxIterations","strictIntegers","fixIntegerDivisionAccuracy","optimizeFloatMemory","tactic","functions","nativeFunctions","injectedNative","debug","randomSeed","returnType"];s.declaredArgumentTypes&&(r.argumentTypes=s.declaredArgumentTypes.slice());for(let e=0;e1?"function (v) { return v[this.thread.z][this.thread.y][this.thread.x]; }":t[1]>1?"function (v) { return v[this.thread.y][this.thread.x]; }":"function (v) { return v[this.thread.x]; }",a=t[2]>1?[t[0],t[1],t[2]]:t[1]>1?[t[0],t[1]]:[t[0]];n=this.gpu.createKernel(i,{output:a,pipeline:!0,immutable:!1}),e.genericClones.set(r,n)}return n(s)}_genericEagerUploadsPay(e){return 0!==e.kernels.length&&"gpu"===e.kernels[0].clone.kernel.constructor.mode}_eagerUploads(e,t){const r=new Array(t.length).fill(null);for(let n=0;n0?e.kernels[0].clone.kernel.constructor.mode:null,a="gpu"===i||"webgpu"===i,o=r||new Array(t.length).fill(null);if(a&&!r)for(let r=0;r{const{utils:s}=i(),{Input:n}=r(),{getActiveTrace:a}=pt();function o(e,t){if(t.kernel)return void(t.kernel=e);const r=s.allPropertiesOf(e);for(let s=0;st.kernel[n]),t.__defineSetter__(n,e=>{t.kernel[n]=e})))}t.kernel=e}t.exports={kernelRunShortcut:function(e){function t(t){e.build.apply(e,t),e.checkArgumentTypes(t);let r=e.switchingKernels?void 0:e.run.apply(e,t);for(let n=0;e.switchingKernels;n++){if(n>=4){const t=e.resetSwitchingKernels();throw new Error(`this kernel cannot run the arguments it was given (${s(t)}); it did not settle on a kernel for them after 4 attempts. Create a separate kernel for this call's argument types.`)}const i=e.resetSwitchingKernels(),a=e.onRequestSwitchKernel(i,t,e);p.kernel=e=a,a.checkArgumentTypes(t),r=a.switchingKernels?void 0:a.run.apply(a,t),a.fallbackRequested&&(r=e.run.apply(e,t))}return r}function s(e){return e&&e.length?e.map(e=>"argumentTypeMismatch"===e.type?`argument ${e.index} is now ${e.needed}`:e.type).join(", "):"unknown reason"}function r(s){if(e.onAsyncModeUpgrade){const t=e.onAsyncModeUpgrade;e.onAsyncModeUpgrade=null;const n=l(s);return t(n,e).then(e=>(e&&p.replaceKernel(e),r(n)))}try{if(!0===e.constructor.isAsync)return e.build.apply(e,s),Promise.resolve(e.run.apply(e,s));for(let e=0;er(e));const n=t(s);return e.renderKernels?Promise.resolve(e.renderKernels()):e.renderOutput?e.renderOutputAsync?e.renderOutputAsync():Promise.resolve(e.renderOutput()):Promise.resolve(n)}catch(e){return Promise.reject(e)}}function i(e){return Boolean(e)&&"WebGPUBuffer"===e.type}function u(e){const t=l(e),s=[];for(let e=0;e{t[r]=e}))}return Promise.all(s).then(()=>t)}function l(e){const t=new Array(e.length);for(let s=0;s{try{e(c.apply(this,arguments))}catch(e){t(e)}})},p.replaceKernel=function(t){o(e=t,p)},o(e,p),p}}}),ft=e((e,s)=>{const{gpuMock:r}=t(),{utils:n}=i(),{Kernel:o}=a(),{CPUKernel:u}=p(),{HeadlessGLKernel:l}=ve(),{WebGL2Kernel:h}=tt(),{WebGLKernel:c}=be(),{WebGPUKernel:d}=it(),{WebAssemblyKernel:f}=lt(),{kernelRunShortcut:m}=dt(),{Pipeline:g}=pt(),y=[l,h,c,f],x=["gpu","cpu"],b={headlessgl:l,webgl2:h,webgl:c,webgpu:d,webasm:f};let v=!0;function S(e){if(!e)return{};const t=Object.assign({},e);return e.hasOwnProperty("floatOutput")&&(n.warnDeprecated("setting","floatOutput","precision"),t.precision=e.floatOutput?"single":"unsigned"),e.hasOwnProperty("outputToTexture")&&(n.warnDeprecated("setting","outputToTexture","pipeline"),t.pipeline=Boolean(e.outputToTexture)),e.hasOwnProperty("outputImmutable")&&(n.warnDeprecated("setting","outputImmutable","immutable"),t.immutable=Boolean(e.outputImmutable)),e.hasOwnProperty("floatTextures")&&(n.warnDeprecated("setting","floatTextures","optimizeFloatMemory"),t.optimizeFloatMemory=Boolean(e.floatTextures)),t}s.exports={GPU:class e{static disableValidation(){v=!1}static enableValidation(){v=!0}static get isGPUSupported(){return y.some(e=>e.isSupported)}static get isKernelMapSupported(){return y.some(e=>e.isSupported&&e.features.kernelMap)}static get isOffscreenCanvasSupported(){return"undefined"!=typeof Worker&&"undefined"!=typeof OffscreenCanvas||"undefined"!=typeof importScripts}static get isWebGLSupported(){return c.isSupported}static get isWebGL2Supported(){return h.isSupported}static get isHeadlessGLSupported(){return l.isSupported}static get isWebGPUSupported(){return d.isSupported}static isWebGPUAvailable(){return d.isSupported?navigator.gpu.requestAdapter().then(e=>null!==e,()=>!1):Promise.resolve(!1)}static get isWebAssemblySupported(){return f.isSupported}static get isCanvasSupported(){return"undefined"!=typeof HTMLCanvasElement}static get isGPUHTMLImageArraySupported(){return h.isSupported}static get isSinglePrecisionSupported(){return y.some(e=>e.isSupported&&e.features.isFloatRead&&e.features.isTextureFloat)}constructor(t){if(t=t||{},this.canvas=t.canvas||null,this.context=t.context||null,this.mode=t.mode,this.Kernel=null,this._webGPUDecision=null,"async"===t.mode&&(d.isSupported?e.isWebGPUAvailable().then(e=>{this._webGPUDecision=e},()=>{this._webGPUDecision=!1}):this._webGPUDecision=!1),this.kernels=[],this.pipelines=[],this.functions=[],this.nativeFunctions=[],this.injectedNative=null,"dev"!==this.mode){if(this.chooseKernel(),t.functions)for(let e=0;es.argumentTypes[e]));const l=this;function h(e){console.warn("Falling back to CPU"+(y.fallbackReason?`: ${y.fallbackReason}`:""));const s=new u(t,{argumentTypes:y.argumentTypes,constantTypes:y.constantTypes,graphical:y.graphical,loopMaxIterations:y.loopMaxIterations,constants:y.constants,dynamicOutput:y.dynamicOutput,dynamicArgument:y.dynamicArguments,output:y.output,precision:y.precision,pipeline:y.pipeline,immutable:y.immutable,optimizeFloatMemory:y.optimizeFloatMemory,fixIntegerDivisionAccuracy:y.fixIntegerDivisionAccuracy,functions:y.functions,nativeFunctions:y.nativeFunctions,injectedNative:y.injectedNative,subKernels:y.subKernels,strictIntegers:y.strictIntegers,randomSeed:y.randomSeed,debug:y.debug,asyncMode:y.asyncMode,onRequestFallback:h,onRequestSwitchKernel:c,canvas:y.graphical&&!y.context?y.canvas:null});s.fallbackReason=y.fallbackReason,s.build.apply(s,e);const r=s.run.apply(s,e);return y.replaceKernel(s),!l.canvas&&s.canvas&&(l.canvas=s.canvas),!l.context&&s.context&&(l.context=s.context),r}function c(e,s,r){r.debug&&console.warn("Switching kernels");let n=null;if(r.signature&&!a[r.signature]&&(a[r.signature]=r),r.dynamicOutput)for(let t=e.length-1;t>=0;t--){const s=e[t];"outputPrecisionMismatch"===s.type&&(n=s.needed)}const o=r.constructor,u=o.getArgumentTypes(r,s),l=o.getSignature(r,u),p=a[l];if(p)return p.onActivate(r),p;const d=a[l]=new o(t,{argumentTypes:u,constantTypes:r.constantTypes,graphical:r.graphical,loopMaxIterations:r.loopMaxIterations,constants:r.constants,dynamicOutput:r.dynamicOutput,dynamicArgument:r.dynamicArguments,context:r.context,canvas:r.canvas,output:n||r.output,precision:r.precision,pipeline:r.pipeline,immutable:r.immutable,optimizeFloatMemory:r.optimizeFloatMemory,fixIntegerDivisionAccuracy:r.fixIntegerDivisionAccuracy,functions:r.functions,nativeFunctions:r.nativeFunctions,injectedNative:r.injectedNative,subKernels:r.subKernels,strictIntegers:r.strictIntegers,randomSeed:r.randomSeed,debug:r.debug,asyncMode:r.asyncMode,gpu:r.gpu,validate:v,returnType:r.returnType,tactic:r.tactic,onRequestFallback:h,onRequestSwitchKernel:c,texture:r.texture,mappedTextures:r.mappedTextures,drawBuffersMap:r.drawBuffersMap});return d.build.apply(d,s),y.replaceKernel(d),i.push(d),d}const p=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate:v,onRequestFallback:h,onRequestSwitchKernel:c},o);"async"===this.mode&&(p.asyncMode=!0);let f,g=this.Kernel;"async"===this.mode&&o.graphical&&!0===this._webGPUDecision&&(g=d,p.canvas===this.canvas&&(p.canvas=o.canvas||null),p.context===this.context&&(p.context=o.context||null),p.asyncMode=!0);try{f=new g(t,p)}catch(e){if(g===this.Kernel)throw e;f=new this.Kernel(t,Object.assign({},p,{canvas:this.canvas,context:this.context}))}const y=m(f);if("async"===this.mode&&d.isSupported&&!(f instanceof d)){const s=this;f.onAsyncModeUpgrade=function(r,n){return e.isWebGPUAvailable().then(e=>{if(!e)return null;if(n.graphical)return n.debug&&console.warn("webgpu upgrade declined: graphical kernels keep their canvas"),null;let a;try{a=new d(t,{functions:n.functions,nativeFunctions:n.nativeFunctions,injectedNative:n.injectedNative,gpu:s,validate:v,asyncMode:!0,output:n.output,pipeline:n.pipeline,immutable:n.immutable,dynamicOutput:n.dynamicOutput,dynamicArguments:!0,loopMaxIterations:n.loopMaxIterations,constants:n.constants,constantTypes:n.constantTypes,argumentTypes:n.argumentTypes,precision:n.precision,tactic:n.tactic,strictIntegers:n.strictIntegers,fixIntegerDivisionAccuracy:n.fixIntegerDivisionAccuracy,subKernels:n.subKernels,graphical:n.graphical,debug:n.debug}),a.build.apply(a,r)}catch(e){return n.debug&&console.warn("webgpu upgrade declined: "+e.message),null}return a._buildPromise.then(()=>(i.push(a),a),e=>(n.debug&&console.warn("webgpu upgrade declined: "+e.message),a.destroy(),null))},()=>null)}}return this.canvas||(this.canvas=f.canvas),this.context||(this.context=f.context),i.push(f),y}createPipeline(e,t){if("function"!=typeof e)throw new Error("createPipeline requires an orchestration function");if("dev"===this.mode)throw new Error("createPipeline is not supported in dev mode");const s=new g(this,e,t);this.pipelines.push(s);const r=function(){return s.call(arguments)};return r.pipeline=s,r.setConstants=function(e){return s.setConstants(e),r},r.destroy=function(){return s.destroy()},Object.defineProperty(r,"executorKind",{get:()=>s.executorKind}),Object.defineProperty(r,"fallbackReason",{get:()=>s.fallbackReason}),Object.defineProperty(r,"plan",{get:()=>s.plan}),Object.defineProperty(r,"backend",{get:()=>{const e=s.executorKind;if("fused-sync"===e||"fused-threaded"===e)return"webasm";if("fused-encoder"===e)return"webgpu";const t=s.plan;if(!t)return null;for(const[e,s]of t.genericClones)if(0!==e.indexOf("up:"))return s.kernel.constructor.mode;return t.kernels.length>0?t.kernels[0].clone.kernel.constructor.mode:null}}),r}createKernelMap(){let e,t;const s=typeof arguments[arguments.length-2];if("function"===s||"string"===s?(e=arguments[arguments.length-2],t=arguments[arguments.length-1]):e=arguments[arguments.length-1],!("dev"===this.mode||this.Kernel.isSupported&&this.Kernel.features.kernelMap)){if("webgpu"===this.Kernel.mode)throw new Error("WebGPU backend does not yet support createKernelMap");if(this.mode&&x.indexOf(this.mode)<0&&"webasm"!==this.Kernel.mode)throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}const r=S(t);if(t&&"object"==typeof t.argumentTypes&&(r.argumentTypes=Object.keys(t.argumentTypes).map(e=>t.argumentTypes[e])),Array.isArray(arguments[0])){r.subKernels=[];const e=arguments[0];for(let t=0;t0)throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.');return this.nativeFunctions.push(Object.assign({name:e,source:t},s)),this}injectNative(e){return this.injectedNative=e,this}destroy(){return new Promise((e,t)=>{this.kernels||e(),setTimeout(()=>{try{let s=Promise.resolve();if(this.pipelines){const e=this.pipelines.slice();s=Promise.all(e.map(e=>Promise.resolve(e.destroy()).catch(()=>{})))}const r=()=>{try{const e=this.kernels.slice();for(let t=0;t{const{utils:s}=i();t.exports={alias:function(e,t){const r=t.toString();return new Function(`return function ${e} (${s.getArgumentNamesFromString(r).join(", ")}) {\n ${s.getFunctionBodyFromString(r)}\n}`)()}}}),gt=e((e,t)=>{const{GPU:s}=ft(),{alias:c}=mt(),{utils:d}=i(),{Input:f,input:m}=r(),{Texture:g}=n(),{FunctionBuilder:y}=o(),{FunctionNode:x}=l(),{CPUFunctionNode:b}=h(),{CPUKernel:v}=p(),{HeadlessGLKernel:S}=ve(),{WebGLFunctionNode:T}=N(),{WebGLKernel:A}=be(),{kernelValueMaps:w}=xe(),{WebGL2FunctionNode:_}=Se(),{WebGL2Kernel:E}=tt(),{kernelValueMaps:I}=et(),{WGSLFunctionNode:k}=st(),{WebGPUKernel:C}=it(),{WebGPUContext:L}=rt(),{WebGPUBufferResult:D}=nt(),{WebAssemblyFunctionNode:F}=ot(),{WebAssemblyKernel:$}=lt(),{GLKernel:G}=R(),{Kernel:O}=a(),{FunctionTracer:V}=u();t.exports={alias:c,CPUFunctionNode:b,CPUKernel:v,GPU:s,FunctionBuilder:y,FunctionNode:x,HeadlessGLKernel:S,Input:f,input:m,Texture:g,utils:d,WebGL2FunctionNode:_,WebGL2Kernel:E,webGL2KernelValueMaps:I,WebGLFunctionNode:T,WebGLKernel:A,webGLKernelValueMaps:w,WGSLFunctionNode:k,WebGPUKernel:C,WebGPUContext:L,WebGPUBufferResult:D,WebAssemblyFunctionNode:F,WebAssemblyKernel:$,GLKernel:G,Kernel:O,FunctionTracer:V,plugins:{mathRandom:M()}}});return e((e,t)=>{const s=gt(),r=s.GPU;for(const e in s)s.hasOwnProperty(e)&&"GPU"!==e&&(r[e]=s[e]);function n(e){e.GPU&&e.GPU.prototype&&e.GPU.prototype.createKernel||Object.defineProperty(e,"GPU",{configurable:!0,get:()=>r,set(){}})}r.GPU=r,"undefined"!=typeof window&&n(window),"undefined"!=typeof self&&n(self),t.exports=r})()}); \ No newline at end of file diff --git a/src/pipeline.js b/src/pipeline.js index 9e5c589a..dece5dae 100644 --- a/src/pipeline.js +++ b/src/pipeline.js @@ -367,7 +367,10 @@ class Pipeline { // snapshot and the deep copy is skipped -- copying was a fixed ~30 ms // per call on image-sized arguments, which dominated short plans let preUploaded = null; - if (this._inFlight === 0 && this.plan && this._executor === null && this._genericEagerUploadsPay(this.plan)) { + // _executor === false is the settled has-degraded-to-generic sentinel + // (null was never it -- the first cut of this test made the fast path + // dead code on exactly the GL rows it was built for) + if (this._inFlight === 0 && this.plan && this._executor === false && this._genericEagerUploadsPay(this.plan)) { preUploaded = this._eagerUploads(this.plan, args); } for (let i = 0; i < args.length; i++) { @@ -702,6 +705,15 @@ class Pipeline { const value = args[binding.index]; if (!value || typeof value !== 'object') continue; if (typeof value.toArray === 'function' && !(value instanceof Input)) continue; + // size drift rebuilds the clones in the tail; an eager upload into + // the OLD upload kernel would write out of bounds -- decline and + // let the copy path carry this call + if (plan.genericArgDims) { + const known = plan.genericArgDims.get(binding.index); + if (known !== undefined && known !== argDimensions(value).join('x')) { + return null; + } + } const handle = this._uploadArg(plan, binding.index, value); if (handle && typeof handle.then === 'function') { // not synchronous after all: abandon the fast path for this call diff --git a/test/features/pipeline/lifecycle.js b/test/features/pipeline/lifecycle.js index 6c140a11..1a2e6977 100644 --- a/test/features/pipeline/lifecycle.js +++ b/test/features/pipeline/lifecycle.js @@ -236,6 +236,9 @@ test('eager-upload fast path keeps call-time sampling headlessgl', async assert const k = gpu.createKernel(function (a) { return a[this.thread.x] + 1; }, { output: [4] }); const p = gpu.createPipeline(function (v) { return k(v); }); await p([1, 2, 3, 4]); // plan built; pipeline quiescent -> next call is eager + // the settled-generic sentinel is what arms the fast path; testing null + // instead of false once made it dead code on every GL pipeline + assert.equal(p.pipeline._executor, false, 'eager fast path arms after generic settles'); const data = new Float32Array([10, 20, 30, 40]); const pending = p(data); data.fill(0); // mutated between call and settlement From 0dc80701b64efa7b49ba6b64fd02db927519fe7b Mon Sep 17 00:00:00 2001 From: Fazli Sapuan Date: Mon, 3 Aug 2026 18:10:19 +0800 Subject: [PATCH 16/16] =?UTF-8?q?docs(pipeline):=20per-backend=20benefits?= =?UTF-8?q?=20=E2=80=94=20webgpu=20and=20GL=20join=20the=20numbers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01RUTVDFaHav3uAdN3XfZLyx --- README.md | 2 ++ dist/gpu-browser-core.js | 2 +- dist/gpu-browser-core.min.js | 2 +- dist/gpu-browser.js | 2 +- dist/gpu-browser.min.js | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eb7767bc..7253293a 100644 --- a/README.md +++ b/README.md @@ -1402,6 +1402,8 @@ Introspection is **supported API**, not plan internals — it exists precisely s What the fusion buys, measured on the gauntlet's jacobi and heat benches rewritten via `createPipeline` (checksums identical to the per-pass versions): **5.7× on heat threaded, 5.2× on jacobi** (heat 890 ms vs 5073 ms per-pass, jacobi 387 ms vs 1997 ms — and 2.8×/3.2× over plain JavaScript on rows the webasm backend previously lost), against the same kernels called per pass on webasm. The per-pass costs it deletes are exactly the ones that dominate short passes — a task round-trip through the worker pool per call, argument re-upload, and a readback per step — leaving the arithmetic, which was already SIMD. +On **webgpu** the same benches run **1.55–1.62×** over per-pass chaining (jacobi 28 ms vs 44, heat 37 vs 60) — a smaller multiplier because webgpu's per-pass baseline already pipelines on the GPU queue; the encoder fusion removes the per-call JS, bind, and submit overhead that remains, and long chains feel it most (a 12,289-pass wavefront ran **10× faster** migrated). On the **GL backends** the generic executor runs at parity with a hand-rolled two-kernel ping-pong — the pattern it generates for you — so the ergonomic win is the whole win there: one kernel and a plain loop replace duplicate kernels, upload kernels, and manual texture juggling, with identical results and no leaked per-step textures. + Not in v1, stated plainly: * **No mid-plan readback.** The plan runs start to finish; you cannot inspect an intermediate and stop early. The name `this.check` on the orchestration context is **reserved** for this: the future design records `this.check(handle, predicate)` as a checkpoint step where the executor reads back a small reduction every N passes and ends the plan early when the predicate answers converged — residual thresholds in iterative solvers, without surrendering the fused loop. Nothing you write today should put a `check` on the orchestration `this`. diff --git a/dist/gpu-browser-core.js b/dist/gpu-browser-core.js index 547b665d..11750131 100644 --- a/dist/gpu-browser-core.js +++ b/dist/gpu-browser-core.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 18:10:17 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser-core.min.js b/dist/gpu-browser-core.min.js index c94cc3f3..59aa1979 100644 --- a/dist/gpu-browser-core.min.js +++ b/dist/gpu-browser-core.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 18:10:17 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.js b/dist/gpu-browser.js index c58a9649..b6b1a43e 100644 --- a/dist/gpu-browser.js +++ b/dist/gpu-browser.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 18:10:17 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License diff --git a/dist/gpu-browser.min.js b/dist/gpu-browser.min.js index d5d6342a..97b0ce1f 100644 --- a/dist/gpu-browser.min.js +++ b/dist/gpu-browser.min.js @@ -5,7 +5,7 @@ * GPU Accelerated JavaScript * * @version 2.22.0 - * @date Mon Aug 03 2026 17:41:54 GMT+0800 (Singapore Standard Time) + * @date Mon Aug 03 2026 18:10:17 GMT+0800 (Singapore Standard Time) * * @license MIT * The MIT License